loyalflow
loyalflow

Reputation: 14919

How to add 2 of the same properties to a Model?

Say I have a class like:

public class User
{
..
}

public class ProductSale
{

   [ForeignKey("User")]
   public int CreatedByUserId {get;set;}

   [ForeignKey("User")]
   public int UpdatedByUserId {get;set;


   public virtual User CreatedByUser {get;set;}
   public virtual User ModifiedByUser {get;set}
}

How will entity framework figure out which property to use for CreatedByUser and ModifiedByUser?

Upvotes: 0

Views: 53

Answers (2)

AContractor
AContractor

Reputation: 176

You also need to assign the value of the User yourself. EF can't automatically figure out who the CreatedBy and UpdatedBy user is.

Upvotes: 0

Jurica Smircic
Jurica Smircic

Reputation: 6455

You need to specify navigation property name in the foreign key attribute, not the class name.

public class ProductSale
{

  [ForeignKey("CreatedByUser")]
  public int CreatedByUserId {get;set;}

  [ForeignKey("ModifiedByUser")]
  public int UpdatedByUserId {get;set;


  public virtual User CreatedByUser {get;set;}
  public virtual User ModifiedByUser {get;set}
}

Upvotes: 3

Related Questions