如何在ADO.Net实体模型中将具有外键的表更新到另一个表?

我有2个表,Table1有一个主键’CustomizationId’,而Table2有一个与之匹配的FK Customizationid。 表2没有主键。

我正在尝试从基于Web的表单添加新记录。 我试图将其保存到数据库,我收到一个错误:

Customization customization = new Customization(); Code code = new Code(); customization.Name = CustomizationName.Text; customization.LastUpdated = DateTime.Now; code.Top = top_js.InnerText; code.Bottom = bottom_js.InnerText; //code.CustomizationId = customization.CustomizationId; customization.Code = code; entities.AddToCustomizations(customization); entities.SaveChanges(); 

当我调用SaveChanges时,无论是否添加注释行,我都会收到错误。

 Unable to update the EntitySet 'Code' because it has a DefiningQuery and no  element exists in the  element to support the current operation. 

我该如何处理这种情况? 我只想在我添加自定义的同时添加代码。 “代码”表应将Customizationid设置为Customization设置的PK / Identity。

有任何想法吗?

就EF而言,没有PK的表是View。

这意味着您有两种选择:

  1. 告诉一个小小的谎言,并说服EF说’视图’是一张桌子
  2. 添加修改function (插入/更新/删除),以便您可以编辑它们。

通常修改函数是存储过程,但如果您无权访问数据库,则可以直接将T-SQL添加到SSDL中…

就是每个动作(插入,更新和删除)在EDMX的元素中的类似内容:

   INSERT dbo.TCode(ID, Name) VALUES (@ID, @Name)     

在SSDL中具有修改function后,您需要映射它们,以便EF根据需要使用它们。

在你的情况下,我建议(1)。

希望这可以帮助。

干杯亚历克斯