简体   繁体   中英

Entity Framework ApplicationUser more than once in a class

EF: 6.0 Code First .NET: 4.5.2 VS2015

I need the scenario where 2 users are on a Board . There can be many boards, so Tom could be a Grantor on a board and Mary be a Claimer . Yet on another board Mary could be a Grantor and Tom could be a Claimer .

To get around there being 2 ApplicationUsers in the same model, I derived from 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; }
}

And then created the Board class:

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; }
}

And added the DbSet of:

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

This added 2 tables to the db of GrantorUsers and ClaimerUsers with only ID fields.

Is this the wrong way of looking designing this schema? Or if it is correct, how can Tom be an ApplicationUser all the time, but then when I create a board make him either a Grantor or a 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();

This is the idea I'm after, but know it must be done in a different way. On the next board Tom could be a Claimer and Mary a Claimer.

I think it's not exactly the c# question but anyway. You need use roles, user groups. Example of "Fast way": In database store table "Roles" with struct |UserId|BoardId|Role|. When "Tom" visit a board your programm check this table and assign proper role. So he can have different roles for different boards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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