简体   繁体   中英

EntityFramework: Add row function with row values as parameters

I have recently used EntityFramework to replace the use of DataSet. There's one function in the dataset that is missing in EntityFramework.

With dataset I have the AddRow method out-of-the-box available:

this.DataSet.CustomerDataTable.AddCustomerRow(int cId, int Name, int Telephone, ...)

This function is auto-generated, with each column from the table mapped to a parameter. It is very useful 'coz I won't forget any column. But with EntityFramework, this is what I can do:

Customer newCustomer = new Customer();
newCustomer.Name = "John";
newCustomer.Telephone = "04xxxxxxxx";
...
context.Customers.Add(newCustomer );

It is easy to forget to assigne value to one of the fields if not for the parameterized AddRow method. As I can't find the auto-generated AddEntity function I have to write my own. I was told this function is generated with EntityFramework 4. I'm using 6.1.1 and can't find it.

Could you please tell me how to find this method or achieve similar result without having to write a method by myself?

Maybe you are looking for the model binding of Asp.net MVC Framework

Quote from MSDN

DbSet.Add Method

Adds the given entity to the context underlying the set in the Added state such that it will be inserted into the database when SaveChanges is called.

By the way, your question is not very clear, in a common MVC scenario, for example, the mapping of your model is done by Model Binder

So, if you have to add a News to your DbSet

 public ActionResult Create([Bind(Include = "Title,Body,SubTitle")]News model){
  if (ModelState.IsValid){
    ApplicationDbContext.News.Add(model);
    ApplicationDbContext.News.SaveChanges();

  }
}

The hard work of binding is done completely by Model Binder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM