在同一实体User中添加ICollection User

时间:2016-10-16 14:45:50

标签: c# .net entity-framework code-first

是否可能如此:它是一个Messenger,其中收集Friends的实体User content ICollection User来自同一个用户? 如果可能,请告诉我如何在DbContext文件中创建它们之间的正确关系? 或者如何更好地建立这种关系。可能会创建单独的实体? 提前谢谢!

namespace Tinkl.Data.Core.Domain
{
    public class User
    {
        public User()
        {
            Contacts = new List<User>();
            Conversations = new List<Conversation>();
            Invites = new List<User>();
        }

        public int UserId { get; set; }
        public string NickName { get; set; }
        public string EMail { get; set; }
        public string Password { get; set; }
        public DateTime? CreationDate { get; set; }
        public DateTime? ExitDate { get; set; }
        public string Picture { get; set; }
        public string Status { get; set; }
        public virtual ICollection<User> Invites { get; set; }
        public virtual ICollection<User> Contacts { get; set; }
        public virtual ICollection<Conversation> Conversations { get; set; }
    }
}

1 个答案:

答案 0 :(得分:1)

你正朝着正确的方向前进,首先在EF代码中看到我的下面代码相同类型的自我关系

public class ContentEntityRef : BaseModel
{
    public ContentEntityRef()
    {
        RoleRefs = new HashSet<RoleRef>();
    }

    public int EntityId { get; set; }

    public string EntityName { get; set; }

    public int? ParentEntityId { get; set; }

    public virtual ICollection<RoleRef> RoleRefs { get; set; }

    public virtual ContentEntityRef Parent { get; set; }

    public virtual ICollection<ContentEntityRef> Children { get; set; }
}

我创建了seprate配置文件,你可以在dbContext中使用“OnModelCreating”方法。

internal class ContentEntityRefConfiguration : EntityTypeConfiguration<ContentEntityRef>, IEntityConfiguration
{
    public ContentEntityRefConfiguration()
    {
        this.HasKey(x => x.EntityId).Property(t => t.EntityId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        this.Property(x => x.EntityName).IsRequired().HasMaxLength(50);

        this.HasMany(c => c.Children).WithOptional(c => c.Parent).HasForeignKey(c => c.ParentEntityId);

        this.HasMany<RoleRef>(role => role.RoleRefs)
           .WithMany(content => content.ContentEntities)
           .Map(contentRole =>
           {
               contentRole.MapLeftKey("EntityID");
               contentRole.MapRightKey("RoleID");
               contentRole.ToTable("RoleEntityMap");
           });
    }
}

希望这会对你有所帮助:)。