简体   繁体   English

EntityFramework:添加以行值作为参数的行函数

[英]EntityFramework: Add row function with row values as parameters

I have recently used EntityFramework to replace the use of DataSet. 我最近使用EntityFramework代替了DataSet的使用。 There's one function in the dataset that is missing in EntityFramework. EntityFramework中缺少数据集中的一个功能。

With dataset I have the AddRow method out-of-the-box available: 对于数据集,我可以立即使用AddRow方法:

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: 但是,使用EntityFramework,这是我可以做的:

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. 如果不使用参数化的AddRow方法,很容易忘记将值分配给其中一个字段。 As I can't find the auto-generated AddEntity function I have to write my own. 由于找不到自动生成的AddEntity函数,因此必须编写自己的函数。 I was told this function is generated with EntityFramework 4. I'm using 6.1.1 and can't find it. 有人告诉我此功能是通过EntityFramework 4生成的。我使用的是6.1.1,找不到它。

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 也许您正在寻找Asp.net MVC框架的模型绑定

Quote from MSDN MSDN引用

DbSet.Add Method DbSet.Add方法

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. 在“已添加”状态下将给定实体添加到集合的基础上下文中,以便在调用SaveChanges时将其插入数据库中。

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 顺便说一句,您的问题不是很清楚,在常见的MVC场景中,例如,模型的映射是由Model Binder完成的

So, if you have to add a News to your DbSet 因此,如果您必须将新闻添加到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 绑定的辛苦工作完全由Model Binder完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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