【问题标题】:Unable to update the EntitySet '' because it has a DefiningQuery无法更新 EntitySet '' 因为它有一个 DefiningQuery
【发布时间】:2017-10-03 03:56:32
【问题描述】:

我在这段代码中遇到了这个错误:

Unable to update the EntitySet 'Ingredient_Quantity' because it has a
DefiningQuery and no <InsertFunction> element exists in the 
<ModificationFunctionMapping> element to support the current operation.

代码。

Ingredient ing = new Ingredient();
ing.name = ingredientVM.name;
ing.Ingredient_Type_id = ingredientVM.typeId;
ing.UOM_id = ingredientVM.uomId;
ing.is_deleted = 0;

db.Ingredients.Add(ing);
db.SaveChanges();

int latestIngredientId = ing.id;

Ingredient_Quantity iq = new Ingredient_Quantity
{
   Ingredient_id = latestIngredientId,
   quantity_as_of = DateTime.Now,
   quantity = (double)ingredientVM.quantity
};

db.Ingredient_Quantity.Add(iq);
db.SaveChanges(); // HERE IS WHERE I'M GETTING THE ERROR

从我在互联网上看到的情况来看,这是因为我的Ingredient_Quantity 将每一列都视为实体键。我不知道这是否正确。

我该如何改变呢?有什么建议吗?

【问题讨论】:

  • 我认为您需要在Ingredient_Quantity 数据库表中设置一列作为主键。尝试将主键添加到Ingredient_id,删除实体并重新添加它。 Ingredient_Quantity 是不是一个视图?
  • 你的意思是像this? “'Ingredient_Quantity' 是一个视图”是什么意思?什么是实体映射?对不起,我真的很陌生。
  • 是的,一个这样的主键。该设置现在有效吗?我只想问Ingredient_Quantity是数据库表还是数据库视图,它们在EF实体映射中使用时有不同的处理方式。
  • 当我尝试将 Ingredient_id 设为主键时出现错误,它具有多重性或其他东西。所以我也尝试让quantity_as_of 成为主键。但它仍然不起作用。 Ingredient_Quantity 是一个数据库表
  • 所以你想说Ingredient_QuantityIngredient 中有外键?我认为您有像Multiplicity conflicts with the referential constraint 这样的错误,如果发生这种情况,请尝试将外键设置为可空类型并将关系设置为 0/1..n(零/一对多)。

标签: asp.net-mvc entity-framework-6


【解决方案1】:

你有两个问题:

1) 中最常见的原因“无法更新EntitySet X,因为它有一个 DefiningQuery" 是实体表在数据库中缺少主键约束。您可以通过 SSMS 表设计器或使用此查询将主键添加到标识列(请注意,主键应仅设置为一列):

ALTER TABLE Ingredient_Quantity ADD CONSTRAINT (Ingredient_id) PRIMARY KEY (Ingredient_id)

请注意,在实体映射期间,没有主键的表被视为视图(EF 使用类来定义表/视图名称和属性来引用每个表/视图列),并且不能插入/更新视图(仅 @ 987654327@ 允许)。

2) 引用约束的多重性冲突通常是指源表列定义与目标表外键冲突。您可以使用以下步骤修复多重性设置:

a) 首先定义关系。关系标准应该是这样的:

  • 如果您有不可为空的外键(例如 int),则为一对多关系
  • 零/一对多关系,如果您有可为空的外键(例如 int?

b) 在设计器中打开 EDMX 文件,右键单击空白设计区域,选择“添加新”=>“关联”。

c) 选择最适合您的外键配置的“多重性”设置(参见下图作为示例)。您可以选择1 (One)0..1 (Zero or One),具体取决于第二个表上的非空/可空外键。

相关问题:

It has a DefiningQuery but no InsertFunction element... err

Problems with multiplicity and EF 6

Entity Framework Database Update First Multiplicity conflicts

【讨论】:

    猜你喜欢
    • 2012-09-01
    • 2012-11-30
    • 1970-01-01
    • 2011-11-26
    • 2011-01-31
    • 2023-04-07
    • 2013-02-25
    • 2010-12-08
    • 2021-03-10
    相关资源
    最近更新 更多