开发者

Update table using Linq and Extension Method

开发者 https://www.devze.com 2022-12-16 03:03 出处:网络
When I try to update table using following code I get error message \"Cannot create an instance of the variable type \'T\' because it does not have the new() constraint\"

When I try to update table using following code I get error message

"Cannot create an instance of the variable type 'T' because it does not have the new() constraint"

How Can I create a new instance and update data in database.

   IEnumerable<BookData> bookData = GetBookData(...);

   BookDataContext bookDB = new BookDataContext ();

   bookDB.UpdateTable<MCDB.BookTable>(bookDB.BookTable,bookData);



class BookTable
{
    public string bookName { get; set; }
    public string  authorName { get; set; }
}
开发者_如何学编程

Extension Method

 public static void UpdateTable<T>(this DataContext context, Table<T> tbl, IEnumerable<BookData> data)
    where T : class
    {
        foreach (var item in data)
        {
            context.GetTable<T>().InsertOnSubmit(new T());
            // Error in above statement 

             // I want to do something like this
             context.GetTable<T>().InsertOnSubmit(new T
                {
                    bName = item.bookName
                    aName = item.authorName,
                });
         }
         context.SubmitChanges();
    }

PS: I know the another way but I want to update table using extension method

using ( BookDataContext bookDB = new BookDataContext ())
{
  //code 
}

Thanks


Have you tried adding a new constraint?

where T : class, new()


Add the constraint where T : new():

public static void UpdateTable<T>(
    this DataContext context, Table<T> tbl,
    IEnumerable<BookData> data
) where T : class, new() {
    // details
}

Note that T can not be abstract, and the new constraint must be the last constraint listed.

Whoa, just noticed this:

context.GetTable<T>().InsertOnSubmit(new T
    {
        bName = item.bookName
        aName = item.authorName,
    }
);

You can not get away this unless you add a constraint to T so that the compiler knows that T has properties named bName and aName. At a minimum you need to specify

where T : BookData, new()

where BookData is a class that has those properties defined. This will specify that T is BookData or derives from BookData and that it has a public parameterless constructor. In this case you can do away with the constraint where T : class. Alternatively you can specify

where T : IBookData, new()

where IBookData is an interface defining the two properties that you are using. This constraint specifies that T is a type that implements IBookData and that it has a public parameterless constructor.

Given that, I don't understand why you are doing this generically.

0

精彩评论

暂无评论...
验证码 换一张
取 消