简体   繁体   English

使用实体框架,如何反映多对多关系并为正在创建的新实体添加存在的实体?

[英]Using Entity Framework, how do I reflect a many to many relationship and add entites that exist to a new entity being created?

I'm new to Entity Framework and am trying to figure things out. 我是Entity Framework的新手,我正在努力解决问题。 I have a database created that's not very complicated. 我创建了一个不太复杂的数据库。 There's about 7 tables and 3 of those are mapping tables to associate one table record w/ another. 大约有7个表,其中3个是映射表,用于关联一个表记录w / other。 The example I'm using here is this: 我在这里使用的例子是这样的:

  • Table User 表用户

    • UserId 用户身份
    • UserName 用户名
  • Table Role 表角色

    • RoleId 角色ID
    • RoleName ROLENAME
  • Table: UserRole 表:UserRole

    • UserId 用户身份
    • RoleId 角色ID

The foreign keys are mapped in my database. 外键映射到我的数据库中。 When I create a new Entity Model inside of VS 2008, the diagram seems to have the relationships correct, but does not create a table for the UserRole table. 当我在VS 2008中创建一个新的实体模型时,该图似乎具有正确的关系,但不会为UserRole表创建一个表。 The relationship is mapped as a Many to Many between User & Role. 用户和角色之间的关系映射为多对多。

My problem is that I can create new users and I can create new roles, but I cannot figure out how to create a new user with an existing role. 我的问题是我可以创建新用户,我可以创建新角色,但我无法弄清楚如何创建具有现有角色的新用户。 Furthermore, the UserRole table is probably not mapped correctly within the model to begin with. 此外,UserRole表可能未在模型中正确映射。 Here's my code so far: 到目前为止,这是我的代码:

ObjectQuery<Role> roles = context.Roles;
Role role = context.Roles.Where(c => c.RoleName == "Subscriber").First();

 User user = new User
 { 
  DisplayName = "TestCreate2",
  Email = "test@test.com",
  Password = "test"
 };            
 context.AttachTo("Roles", role);
 user.Roles.Add(role);            
 context.AddToUsers(user);
 context.SaveChanges();

Here's the error I am getting: 这是我得到的错误:

Unable to update the EntitySet 'UserRoles' because it has a DefiningQuery and no element exists in the element to support the current operation. 无法更新EntitySet的“UserRoles”,因为它具有DefiningQuery,并且元素中不存在支持当前操作的元素。

Here is the xml that pertains to the UserRole table: 这是与UserRole表有关的xml:

<EntitySet Name="UserRoles" EntityType="RememberTheJourneyModel.Store.UserRoles" store:Type="Tables" store:Schema="dbo" store:Name="UserRoles">
        <DefiningQuery>SELECT 
  [UserRoles].[Role_id] AS [Role_id], 
  [UserRoles].[User_id] AS [User_id]
  FROM [dbo].[UserRoles] AS [UserRoles]</DefiningQuery>
      </EntitySet>

It was pulling teeth just to figure out how to query the context such that it gave me an actual Role entity. 它只是为了弄清楚如何查询上下文,以便它给了我一个实际的角色实体。 I'm sure the issue is something to do with how UserRole is mapped, but I'm just getting started here and haven't any idea where that might have gone wrong. 我确定这个问题与UserRole的映射方式有关,但我刚开始在这里开始并且不知道哪里可能出错了。

And I really have searched google & this site, but I suppose I haven't come up with the right search parameters to find a question that helps me fix this. 我真的已经搜索了谷歌和这个网站,但我想我没有想出正确的搜索参数来找到一个问题来帮助我解决这个问题。 I found one question that said EF has issues with this, but if you're mapping table makes both columns a primary key, it works itself out. 我发现一个问题,说EF有这个问题,但如果你是映射表使两列成为主键,它就会自行解决。 I'm not sure how to do that. 我不知道该怎么做。 Is this done in the database (using SQL SERVER 2005 EXPRESS) or in the mapping? 这是在数据库中完成的(使用SQL SERVER 2005 EXPRESS)还是在映射中完成? This is a personal project so I can post more details about the code or xml if needed. 这是一个个人项目,因此我可以根据需要发布有关代码或xml的更多详细信息。 Any and all help will be appreciated. 任何和所有帮助将不胜感激。

I remember running into this issue before as well... and I believe I fixed it by making both columns keys in my association table. 我记得之前遇到过这个问题......我相信我通过在关联表中创建两个列键来修复它。

You can make both columns the primary key in SQL Server Management Studio table designer. 您可以将这两列作为SQL Server Management Studio表设计器中的主键。 Just highlight both the User_Id and Role_Id at the same time, right click on the left and select Primary Key... this will make it so that no record can have the same combination of User_Id and Role_Id.. making each entry unique. 只需同时突出显示User_Id和Role_Id,右键单击左侧并选择Primary Key ...这将使得没有记录可以具有User_Id和Role_Id的相同组合..使每个条目都是唯一的。

Then you can update your data model in the Entity Framework designer.. and hopefully be good to go. 然后,您可以在Entity Framework设计器中更新您的数据模型..并希望很好。

I believe that if a table does not have any keys defined to ensure records are unique, then EF would not be able to update records properly, and so the framework guards against that case. 我相信如果一个表没有定义任何键以确保记录是唯一的,那么EF将无法正确更新记录,因此框架可以防范该情况。

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

相关问题 如何在Entity Framework 5中表达“有很多通过”的关系? - How do I express a “has many through” relationship in Entity Framework 5? 如何与实体框架建立一对多关系? - How do I represent a one to many relationship with the Entity Framework? 实体框架多对多关系添加/更新 - Entity Framework many to many relationship add/update 如何通过Entity Framework 6在代码中添加多对多关系? - How to add many to many relationship through Entity Framework 6, in code? 如何在实体框架中添加或删除多对多关系? - How to add or remove a many-to-many relationship in Entity Framework? 使用实体框架删除多对多关系 - Delete Many to Many relationship using Entity Framework 使用 MVC 3 Entity Framework Code-First,如何以一对多的关系创建一个新的“多”object? - Using MVC 3 Entity Framework Code-First, how do you create a new “many” object in a one-to-many relationship? 如何使用具有多对多关系的 Entity Framework Core 5 添加和更新项目? - How do I add and update items using Entity Framework Core 5 that have many to many relationships? 实体框架中有多少关系正在发挥作用 - How many to many relationship in Entity Framework is working 如何与实体框架建立多对多的关系 - How to make many to many relationship with entity framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM