2015-06-20 30 views
2

我有3个实体:EF6,复合键,注释足够了吗?还是我也必须使用Fluent API?

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

正如你所看到的是,UserEvent是刚刚从2个表既有用户ID和事件ID关系表。

我的问题是:

  1. 是注释足以告诉EF创建2个外键?或者我还必须使用Fluent API在DbContext类的OnModelCreating()方法中执行此操作?或者我必须创建一个配置类才能这样做? 我看到这个帖子的东西(这让我困惑):

Entity Framework Multiple Column as Primary Key by Fluent Api

  • ForeignKey的( “X”) 我猜X应该是表名而不是实体的名字,对吗? 例如X应该是AspNetUsers(位于数据库中),而不是AspNetUser,它是实体名称。
  • 谢谢。

    +0

    Annota tions是足够的。您是在创建一对一的关系还是一对多的关系?你使用EF 6吗? – JasonlPrice

    +0

    嗨@JasonlPrice我使用EF 6.用户事件:多对多。所以这就是为什么我需要创建UserEvent实体的原因。 – Franva

    回答

    2

    是的,这是不够的使用数据注释,但问题是,你需要指定在ForeignKey属性导航property`that代表的关系,它是一个外键的名称:

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

    另外,您可以将ForeignKey注释导航性能,并告诉它该属性是关系中的外键:

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

    哈,我明白了。所以X应该是导航属性。谢谢 :) – Franva

    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; } 
    } 
    
    相关问题