0
votes

I have three entities, User, Domain and Role.

I have this class to define the relationship of the three entities:

public class UserDomainRole
{
        [Key]
        public int UserId { get; set; }
        [Key]
        public int DomainId { get; set; }
        [Key]
        public int RoleId { get; set; }
}

So how to I setup a foreign key relationship between UserDomainRole and other three table? Is it something like this?

public class DeniedDomainRole
{
    [Key]
    public int UserId { get; set; }
    public virtual User User { get; set; }
    [Key]
    public int DomainId { get; set; }
    public virtual Domain Domain { get; set; }
    [Key]
    public int RoleId { get; set; }
    public virtual Role Role { get; set; }
}

Then entity framework will work the relationship out?

2

2 Answers

0
votes

This code will give you an exception with a message "Unable to determine composite primary key ordering"

In code first if you want to create a composite primary key then you have to use the to give the key/column order, like that:

[Key, Column(Order=1)]

Where

Order = The composite Primary key/column order on the table

public class UserDomainRole
{
        [Key, Column(Order=1)]
        public int UserId { get; set; }

        [Key, Column(Order=2)]
        public int DomainId { get; set; }

        [Key, Column(Order=3)]
        public int RoleId { get; set; }
}

So how to I setup a foreign key relationship between UserDomainRole and other three table? Is it something like this?

It is depending on what kind of the relationships you have:

  • Configure One-to-Zero-or-One Relationship:

Here, we will configure One-to-Zero-or-One relationship between two entities, e.g. Entity1 can be associated with zero or only one instance of Entity2. http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

  • Configure One-to-Zero-or-One Relationship:

Here, we will configure One-to-Zero-or-One relationship between two entities, e.g. Entity1 can be associated with zero or only one instance of Entity2. http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

  • Configure Many-to-Many relationship:

Here, we will learn how to configure Many-to-Many relationship between the Student and Course entity classes. Student can join multiple courses and multiple students can join one course. http://www.entityframeworktutorial.net/code-first/configure-many-to-many-relationship-in-code-first.aspx

0
votes

In this way you can relation with the user model

public int? UserUserId{get;set;}
public virtual User User{get;set;}

? makes nullable your foreignkey.