实体框架4错误:无法更新EntitySet,因为它具有DefiningQuery [英] Entity Framework 4 Error: Unable to update the EntitySet because it has a DefiningQuery
问题描述
我想做的是从一个表单中添加一个新的类别(其本身完美地工作),同时,将特定用户与新提交的类别相关联。当我尝试这样做,我得到错误在我的主题行。这是我用来尝试这个的代码(ctx是我的实体上下文对象):
public ActionResult Create(Category category ,Guid userId)
{
aspnet_Users user = ctx.aspnet_Users.SingleOrDefault(x => x.UserId == userId);
ctx.Categories.AddObject(category);
user.Categories.Add(category);
ctx.SaveChanges();;
return RedirectToAction(Index);
}
为什么这不工作?
我假设完整的异常消息类似于:
更新EntitySet YourTableName ,因为它有一个DefiningQuery,而且在ModificationFunctionMapping元素中不存在InsertFunction元素以支持当前操作。
如果您的DB表没有定义主键,则会发生这种情况。
将主键添加到表中(使用SQL Server Management Studio或任何),并从数据库更新您的 .edmx
模型。
Okay, here's the scenario. I have 3 tables. One called aspnet_Users one called Categories and a linking table called User_Categories. aspnet_Users and Categories both have primary keys (UserId and ID respectively). The linking table has only two columns: CategoryID and UserId, and there are foreign key relationships setup for each column AND I have a unique key setup for the two columns on User_Categories. This sets up a many-to-many relationship between the aspnet_Users table and the Categories table. I generated my entities edmx file from this database setup, and everything looks perfect and works for almost all operations.
What I want to do is add a new category from a form (which works perfecly by itself), and also, at the same time, associate a specific user with that newly submitted category. When I try to do this I get the error in my subject line. Here is the code I'm using to try this (ctx is my entities context object):
public ActionResult Create(Category category, Guid userId)
{
aspnet_Users user = ctx.aspnet_Users.SingleOrDefault(x => x.UserId == userId);
ctx.Categories.AddObject(category);
user.Categories.Add(category);
ctx.SaveChanges();;
return RedirectToAction("Index");
}
Why doesn't this work?
I assume the full exception message is something similar to:
Unable to update the EntitySet YourTableName because it has a DefiningQuery and no InsertFunction element exists in the ModificationFunctionMapping element to support the current operation.
This will occur if your DB's table doesn't have a primary key defined.
Add a primary key to your table (using SQL Server Management Studio or whatever), and update your .edmx
model from the database.
这篇关于实体框架4错误:无法更新EntitySet,因为它具有DefiningQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!