How to handle an association table linking the same 2 tables

你说的曾经没有我的故事 提交于 2019-12-06 04:48:32

If I well understand, I think I have quite the same: a user is also a group and so can have members.

Here is an extract of my code:

public partial class User : AuthorizableBaseObject, IHasUID {
    public User() {
        Members = new List<User>();
    }

    public Guid UID { get; set; }
    public DateTime EmailValidationDate { get; set; }

    public String EMail { get; set; }

    //public Int64 Id { get; set; }
    public String Login { get; set; }
    public String Password { get; set; }
    public String Description { get; set; }
    public DateTime LastConnectionDate { get; set; }

    public Boolean CanConnect { get; set; }
    public Boolean IsDisabled { get; set; }

    public virtual List<User> Members { get; set; }
}

with the following configuration :

public class UserConfiguration : EntityTypeConfiguration<VDE.User> {
    public UserConfiguration()
        : base() {
        ToTable("Users", "dbo");

        Property(u => u.EMail).IsRequired().HasColumnType("nvarchar").HasMaxLength(100);
        Property(u => u.Login).IsRequired().HasColumnType("nvarchar").HasMaxLength(20);
        Property(u => u.Password).IsRequired().HasColumnType("nvarchar").HasMaxLength(50);
        Property(u => u.Description).HasColumnType("nvarchar").HasMaxLength(200);
        Property(u => u.LastConnectionDate).HasColumnType("datetime2");

        HasMany(u => u.Members).WithMany().Map(m => m.MapLeftKey("UserId").MapRightKey("MemberId").ToTable("UserMembers"));
    }
}

From here to get the members of a group the query is easy:

context.Users.Where(u => u.Id == someId).Select(u => u.Members).FirstOrDefault()

This will give an IEnumerable

Try taking a look at this page on inheritance. Your explanation isn't great, but I think this is what you're trying to achieve.

You must create a class for Impersonation and add it as a DBSet to the dbcontext. EF may make you put a [Key] attribute on the foreign key fields, along with [Column(Order = 0 or 1)].

Then you can lazy load the property:

    public virtual List<Impersonation> UserImpersonations
    {
        get
        {
            if(_userImpersonations == null)
            {
            // Set _userImpersonations = 
            // lazy load using a linq to sql query where 
            // UserImpersonations.UserId = this.UserId
            }

            return __userImpersonations;
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!