2

I have 3 entities:

public class AspNetUser
{
  public string Id {get; set;}
}

public class Event
{
  public int Id {get; set;}
}

public class UserEvent
{
    [Column(Order=0), Key, ForeignKey("AspNetUsers")]
    public string UserId { get; set; }

    [Column(Order=1), Key, ForeignKey("Events")]
    public int EventId { get; set; }

    public DateTime EnrolTime { get; set; }

    public virtual AspNetUser User { get; set; }
    public virtual Event Event { get; set; }
}

As you can see that, the UserEvent is just a relationship table which has both UserId and EventId from 2 tables.

My question is:

  1. Is annotation enough to tell EF to create the 2 foreign keys? Or I have to also use Fluent API to do it in the OnModelCreating() method in the DbContext class? Or I have to create a configuration class to do so? I saw something in this post(it makes me confused):

Entity Framework Multiple Column as Primary Key by Fluent Api

  1. ForeignKey("X") I guess the X should be the table name rather than the entity's name, right? E.g. X should be the AspNetUsers(which is in the database), rather than AspNetUser which is the entity name.

Thank you.

Community
  • 1
  • 1
Franva
  • 6,565
  • 23
  • 79
  • 144
  • Annotations are enough. Are you creating a one-to-one relationship or a one-to-many? Are you you using EF 6? – JasonlPrice Jun 20 '15 at 02:28
  • hi @JasonlPrice I'm using EF 6. User to Event: Many to Many. So that's the reason why I need to create UserEvent entity. – Franva Jun 20 '15 at 04:50

2 Answers2

2

Yes, it's enough using Data Annotations, but the problem is you need to specify in the ForeignKey attribute the name of navigation property`that represents the relationship it is a foreign key for:

public class UserEvent
{
    [ Key,Column(Order=0), ForeignKey("User")]
    public string UserId { get; set; }

    [ Key,Column(Order=1), ForeignKey("Event")]
    public int EventId { get; set; }

    public DateTime EnrolTime { get; set; }

    public virtual AspNetUser User { get; set; }
    public virtual Event Event { get; set; }
}

Alternatively, you can apply the ForeignKey annotation to the navigation property and tell it which property is the foreign key for the relationship:

public class UserEvent
{
    [Key,Column(Order=0)]
    public string UserId { get; set; }

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

    public DateTime EnrolTime { get; set; }

    [ForeignKey("UserId")]
    public virtual AspNetUser User { get; set; }
    [ForeignKey("EventId")]
    public virtual Event Event { get; set; }
}
ocuenca
  • 38,548
  • 11
  • 89
  • 102
0
public class UserEvent
{
    public DateTime EnrolTime { get; set; }

    public string UserId { get; set; }

    [ForeignKey("UserId")]
    public virtual AspNetUser User { get; set; }

    public int EventId { get; set; }

    [ForeignKey("EventId")]
    public virtual Event Event { get; set; }
}
JasonlPrice
  • 187
  • 2
  • 13