在EF核心中创建多对多关系的直接导航属性

时间:2017-09-21 17:20:24

标签: c# sql-server entity-framework asp.net-core entity-framework-core

我一直在研究如何使用Entity Framework Core创建多对多关系:https://docs.microsoft.com/en-us/ef/core/modeling/relationships

我正在制作群组管理功能,我的模型如下:

public class Group
{
    public int GroupId { get; set; }
    public string GroupName { get; set;}            
    public virtual List<GroupMember> GroupMembers { get; set; } = new List<GroupMember>();
}

public class GroupMember
{
    public int GroupId { get; set; }
    public Group Group { get; set; }

    public int UserId { get; set; }
    public User User{ get; set; } 
}

public class User
{
    public int UserId { get; set; }
    public string Email { get; set; }
    public List<GroupMember> MemberOf {get; set;} = new List<GroupMember>();
}

在我的dbContext中,我已经定义了我的连接表,用于映射两个单独的一对多关系:

public DbSet<Group> Groups { get; set; }   
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{ 
                modelBuilder.Entity<GroupMember>()
                    .HasKey(t => new { t.UserId, t.GroupId });

                modelBuilder.Entity<GroupMember>()
                    .HasOne(pt => pt.User)
                    .WithMany(p => p.MemberOf)
                    .HasForeignKey(pt => pt.UserId);

                modelBuilder.Entity<GroupMember>()
                    .HasOne(pt => pt.Group)
                    .WithMany(t => t.GroupMembers)
                    .HasForeignKey(pt => pt.GroupId);
}

我需要创建一个导航属性来直接访问组的成员,而不是必须使用.Include()来包含GroupMembers连接表,然后是第二个.Include()来包含User对象。 / p>

这样做的原因是:a)客户端期望一个组对象具有第一级用户对象数组的属性,并且b)我无法在json中序列化返回的对象,因为它导致用于GroupMember表的group属性的自引用循环。

1 个答案:

答案 0 :(得分:1)

在EF6中,您只需省略链接实体,EF将在幕后创建链接表。

例如

public class Group
{
    public int GroupId { get; set; }
    public string GroupName { get; set;}            
    public virtual List<User> GroupMembers { get; set; } = new List<User>();
}
public class User
{
    public int UserId { get; set; }
    public string Email { get; set; }
    public virtual List<Group> MemberOf {get; set;} = new List<Group>();
}

但是,这并不适用于EF Core。因此,让我们到研讨会,并建立一个解决方法。

一个想法是将NotMapped属性放在为我们提供跳过级别导航属性的实体上,然后忽略JSON序列化中的实际导航属性。同样为了打破周期,一个ContractResolver将跳过&#34;导航属性的序列化&#34;消除对象图中的循环。

像这样:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Newtonsoft.Json;
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json.Serialization;
using System.Reflection;

namespace EFCore2Test
{
    public class Group
    {
        public int GroupId { get; set; }
        public string GroupName { get; set; }
        [JsonIgnore]
        public virtual ICollection<GroupMember> GroupMembers { get; } = new HashSet<GroupMember>();

        [NotMapped]
        public IList<User> Users => GroupMembers.Select(m => m.User).ToList();
    }

    public class GroupMember
    {
        public int GroupId { get; set; }
        public Group Group { get; set; }
        public int UserId { get; set; }
        public User User { get; set; }
    }

    public class User
    {

        public int UserId { get; set; }
        public string Email { get; set; }

        [JsonIgnore]
        public virtual ICollection<GroupMember> MemberOf { get; } = new HashSet<GroupMember>();

        [NotMapped]
        public IList<Group> Groups => MemberOf.Select(m => m.Group).ToList();
    }

    public class Db : DbContext
    {


        public DbSet<User> Users { get; set; }
        public DbSet<Group> Groups { get; set; }

        public DbSet<GroupMember> GroupMembers { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<GroupMember>()
                .HasKey(t => new { t.UserId, t.GroupId });

            modelBuilder.Entity<GroupMember>()
                .HasOne(pt => pt.User)
                .WithMany(p => p.MemberOf)
                .HasForeignKey(pt => pt.UserId);

            modelBuilder.Entity<GroupMember>()
                .HasOne(pt => pt.Group)
                .WithMany(t => t.GroupMembers)
                .HasForeignKey(pt => pt.GroupId);
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Server=(local);Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true");
            base.OnConfiguring(optionsBuilder);
        }
    }


    class Program
    {

        public class DontSerialze<T> : DefaultContractResolver
        {


            protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
            {

                JsonProperty property = base.CreateProperty(member, memberSerialization);

                if (property.PropertyType == typeof(T))
                {
                    property.ShouldSerialize = o => false;
                }

                return property;
            }
        }
        static void Main(string[] args)
        {

            using (var db = new Db())
            {
                db.Database.EnsureDeleted();
                db.Database.EnsureCreated();

                var users = Enumerable.Range(1, 20).Select(i => new User() { Email = $"user{i}@wherever" }).ToList();

                var groups = Enumerable.Range(1, 5).Select(i => new Group() { GroupName = $"group{i}" }).ToList();

                var userGroups = (from u in users from g in groups select new GroupMember() { User = u, Group = g })
                                 .OrderBy(gm => (gm.Group.GroupName + gm.User.Email).GetHashCode())
                                 .Take(100)
                                 .ToList();

                db.Users.AddRange(users);
                db.Groups.AddRange(groups);
                db.GroupMembers.AddRange(userGroups);

                db.SaveChanges();

                var ser = new JsonSerializer();
                ser.Formatting = Formatting.Indented;
                ser.ContractResolver = new DontSerialze<IList<User>>();

                foreach (var u in users.Take(2))
                {
                    ser.Serialize(Console.Out, u);
                    Console.WriteLine();
                }

            }
            Console.WriteLine("Hit any key to exit");
            Console.ReadKey();
        }
    }
}

输出

{
  "UserId": 20,
  "Email": "user1@wherever",
  "Groups": [
    {
      "GroupId": 4,
      "GroupName": "group1"
    },
    {
      "GroupId": 2,
      "GroupName": "group3"
    },
    {
      "GroupId": 5,
      "GroupName": "group4"
    },
    {
      "GroupId": 1,
      "GroupName": "group5"
    },
    {
      "GroupId": 3,
      "GroupName": "group2"
    }
  ]
}
{
  "UserId": 18,
  "Email": "user2@wherever",
  "Groups": [
    {
      "GroupId": 2,
      "GroupName": "group3"
    },
    {
      "GroupId": 1,
      "GroupName": "group5"
    },
    {
      "GroupId": 5,
      "GroupName": "group4"
    },
    {
      "GroupId": 3,
      "GroupName": "group2"
    },
    {
      "GroupId": 4,
      "GroupName": "group1"
    }
  ]
}
Hit any key to exit