gpt4 book ai didi

c# - Entity Framework 不导入具有 super 键的表

转载 作者:行者123 更新时间:2023-11-30 19:20:39 24 4
gpt4 key购买 nike

我有 4 个表:

但是当我创建 Entity Framework 模型时,为什么没有生成tblRoleInProfile

enter image description here

我有一个 Linq TO SQL 模型,想要将其转换为 EF,但现在我的表没有生成。我该如何解决?

更新 1:

您认为我们有一些个人资料和一些角色。如果我们希望配置文件 A 具有角色 1,则在 tblRoleInProperty 中插入一条记录,如果我们希望配置文件 B 没有角色 2(如果存在),则从 tblRoleInProperty 中删除它的记录。我不想删除个人资料。另一个问题是选择新投影。任何机构都可以指导我在 EF 中编写此查询:

var prs = from p in dc.tblProfiles
join rp in dc.tblRoleInProfiles
on p.ProfileId equals rp.ProfileId
join r in dc.tblRoles
on rp.RoleId equals r.RoleId
select new
{
ProfileName = p.ProfileName,
ProfileId = p.ProfileId,
RoleName = r.RoleName,
RoleId = r.RoleId
};

谢谢

最佳答案

这就是 EF 的工作原理。 EF 是 ORM 工具 - 它试图隐藏多对多关系中的持久性细节和联结表正是您不想在对象模型中看到的细节。

您可以将查询重写为:

var prs = from p in dc.tblProfiles
from r in p.tblRoles
select new
{
ProfileName = p.ProfileName,
ProfileId = p.ProfileId,
RoleName = r.RoleName,
RoleId = r.RoleId
};

更新和删除关系也可以通过导航属性进行。

将角色插入配置文件:

// Dummy objects so you do not need to load them from DB first. 
// These objects must exist in database
var p = new Profile { ProfileId = ... };
var r = new Role { RoleId = ... };

context.tblProfiles.Attach(p);
context.tblRoles.Attach(r);

p.tblRoles.Add(r);

context.SaveChanges();

从配置文件中删除角色:

// Dummy objects so you do not need to load them from DB first. 
// These objects must exist in database
var p = new Profile { ProfileId = ... };
var r = new Role { RoleId = ... };

p.tblRoles.Add(r);

context.tblProfiles.Attach(p);
context.tblRoles.Attach(r);

p.tblRoles.Remove(r);
// another approach:
// context.ObjectStateManager.ChangeRelationshipState(p, r, x => x.tblRoles, EntityState.Deleted);

context.SaveChanges();

关于c# - Entity Framework 不导入具有 super 键的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5527522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com