假设我们有以下数据模型:
<code class="language-csharp">public class Member { public int MemberID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual ICollection<MemberComment> MemberComments { get; set; } } public class Comment { public int CommentID { get; set; } public string Message { get; set; } public virtual ICollection<MemberComment> MemberComments { get; set; } } public class MemberComment { [Key, Column(Order = 0)] public int MemberID { get; set; } [Key, Column(Order = 1)] public int CommentID { get; set; } public virtual Member Member { get; set; } public virtual Comment Comment { get; set; } public int Something { get; set; } public string SomethingElse { get; set; } }</code>
不幸的是,Entity Framework Core (EF Core) 不支持使用自定义连接表创建多对多关系。EF Core 自动创建和管理内部连接表,使其不可访问。
要使用具有附加属性(如 MemberComment
)的连接表,我们需要建立两个一对多关系:
(代码段与输入相同,此处省略重复)
现在,我们可以对这些实体执行各种操作:
<code class="language-csharp">// 获取 LastName = "Smith" 的成员的评论 var commentsOfMembers = context.Members .Where(m => m.LastName == "Smith") .SelectMany(m => m.MemberComments.Select(mc => mc.Comment)) .ToList(); // 获取名为“Smith”的成员及其评论 var membersWithComments = context.Members .Where(m => m.LastName == "Smith") .Select(m => new { Member = m, Comments = m.MemberComments.Select(mc => mc.Comment) }) .ToList();</code>
<code class="language-csharp">// 创建成员和两条评论 var member1 = new Member { FirstName = "Pete" }; var comment1 = new Comment { Message = "Good morning!" }; var comment2 = new Comment { Message = "Good evening!" }; var memberComment1 = new MemberComment { Member = member1, Comment = comment1, Something = 101 }; var memberComment2 = new MemberComment { Member = member1, Comment = comment2, Something = 102 }; context.MemberComments.Add(memberComment1); // 也添加 member1 和 comment1 context.MemberComments.Add(memberComment2); // 也添加 comment2 context.SaveChanges();</code>
<code class="language-csharp">// 删除成员和评论之间的关系 var memberComment5 = context.MemberComments .Where(mc => mc.Member.FirstName == "Paul" && mc.Comment.Message == "Good night!") .SingleOrDefault(); if (memberComment5 != null) { context.MemberComments.Remove(memberComment5); context.SaveChanges(); }</code>
以上是如何与EF Core中的其他属性建立多一关系?的详细内容。更多信息请关注PHP中文网其他相关文章!