繁体   English   中英

实体框架ApplicationUser在一个类中不止一次

[英]Entity Framework ApplicationUser more than once in a class

EF: 6.0代码优先。NET: 4.5.2 VS2015

我需要2个用户在Board 董事会可以有很多,所以汤姆可以是董事会的Grantor ,玛丽可以是Claimer 然而在另一个董事会上,玛丽可能是Grantor ,汤姆可能是Claimer

为了避开同一模型中有2个ApplicationUsers,我派生自ApplicationUser

[Table("GrantorUsers")]
public class Grantor : ApplicationUser
{
    public Grantor()
    {
        GrantBoards = new List<Board>();
    }

    public ICollection<Board> GrantBoards { get; set; }
}

[Table("ClaimerUsers")]
public class Claimer : ApplicationUser
{
    public Claimer()
    {
        ClaimBoards = new List<Board>();
    }
    public ICollection<Board> ClaimBoards { get; set; }
}

然后创建Board类:

public class Board
{
    public Board()
    {
        TaskItems = new List<TaskItem>();
        BoardSharedUsers = new HashSet<ApplicationUser>();
    }

    public int Id { get; set; }

    public string Name { get; set; }

    public string ClaimerId { get; set; }
    [ForeignKey("ClaimerId")]
    public Claimer Claimer { get; set; }

    public string GrantorId { get; set; }
    [ForeignKey("GrantorId")]
    public Grantor Grantor { get; set; }

    public int TotalPoints { get; set; }

    public ICollection<TaskItem> TaskItems { get; set; }

    public ICollection<ApplicationUser> BoardSharedUsers { get; set; }
}

并添加了以下DbSet:

public IDbSet<Board> Boards { get; set; }

这将2个表添加到具有ID字段的GrantorUsers和ClaimerUsers的数据库中。

这是设计此架构的错误方式吗? 或者,如果正确的话,Tom怎么会一直都是ApplicationUser,但是当我创建董事会时,让他成为Grantor或Claimer?

var tom = db.Users.Find(id);
var board = new Board {
    GrantorId = tom.Id,
    //...initialize other properties
};

var grantor = new Grantor(tom); //add a copy constructor
                                //and how tough to copy all the
                                //inherited properties from
                                //ApplicationUser's parent base classes

context.Users.Attach(grantor);
context.Boards.Add(board);
context.SaveChanges();

这是我追求的主意,但知道必须以其他方式完成。 在下一局中,汤姆可能是索赔人,玛丽可能是索赔人。

我认为这不完全是C#问题,但无论如何。 您需要使用角色,用户组。 “快速”示例:在数据库存储表“ Roles”中具有结构| UserId | BoardId | Role |。 当“汤姆”访问您的程序板时,请检查此表并分配适当的角色。 因此,他可以在不同的董事会中扮演不同的角色。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM