1

I started working with Entity Framework and I have one BIG problem. I want a many-to-many relation between entities User and Role.

So I created 3 tables User, Role, UserRoles

db

Next I created 3 entities:

public class User
{
    public virtual int UserId { get; protected set; }
    public virtual string UserName { get; set; }
    public virtual string Password { get; set; }
    public virtual DateTime CreateDate { get; set; }
    public virtual ICollection<UserRole> Roles { get; set; }
    public virtual ICollection<UserRole> CreatedRoles { get; set; }
}

public class Role
{
    public virtual int RoleId { get; protected set; }
    public virtual string Name { get; set; }
}

public class UserRole
{
    public virtual int UserRoleId { get; protected set; }
    public virtual int UserId { get; set; }
    public virtual User User { get; set; }

    public virtual int RoleId { get; set; }
    public virtual Role Role { get; set; }
    public virtual DateTime CreateDate { get; set; }

    public virtual int CreateUserId { get; set; }
    public virtual User CreateUser { get; set; }
}

I want to separate mapped user from created user. And In this step Entity Framework start to throw a bugs.

Next I want navigate from User object to his mapped roles and to his created mappings.

Can I configure Entity Framework to do these things?

1
  • I think it is good relation in DB so I want create good Entities in .NET Commented Mar 5, 2016 at 16:07

1 Answer 1

1

You should apply InverseProperty attribute:

public class User
{
    public virtual int UserId { get; protected set; }
    public virtual string UserName { get; set; }
    public virtual string Password { get; set; }
    public virtual DateTime CreateDate { get; set; }

    [InverseProperty("User")]
    public virtual ICollection<UserRole> Roles { get; set; }

    [InverseProperty("CreateUser")]
    public virtual ICollection<UserRole> CreatedRoles { get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.