假設我們有以下數據模型:
<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中文網其他相關文章!