实体框架4错误:无法更新EntitySet,因为它具有DefiningQuery [英] Entity Framework 4 Error: Unable to update the EntitySet because it has a DefiningQuery

查看:253
本文介绍了实体框架4错误:无法更新EntitySet,因为它具有DefiningQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这是这个场景。我有3张桌子一个叫做aspnet_Users,一个叫做Categories,一个称为User_Categories的链接表。 aspnet_Users和Categories都有主键(分别为UserId和ID)。链接表只有两列:CategoryID和UserId,并且每个列都有外键关系设置,我有一个唯一的密钥设置,用于User_Categories上的两列。这将建立aspnet_Users表和Categories表之间的多对多关系。我从这个数据库设置生成了我的实体edmx文件,一切看起来都很完美,适用于几乎所有的操作。



我想做的是从一个表单中添加一个新的类别(其本身完美地工作),同时,将特定用户与新提交的类别相关联。当我尝试这样做,我得到错误在我的主题行。这是我用来尝试这个的代码(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆