【问题标题】:Asp.net mvc entity framework code first associate foreign key with different nameasp.net mvc实体框架代码先将外键与不同名称关联
【发布时间】:2012-04-21 10:22:21
【问题描述】:

如何在此处将具有不同名称的外键关联起来:createdby 在 post 和 UserID 在 users 表中。

public class Post : IValidatableObject
{
    [Key]
    public long PostID { get; set; }

    public long? ParentPostID { get; set; }      


    [ForeignKey("CreatedBy")]  
    public virtual User Users { get; set; }

    [ScaffoldColumn(false)]
    public DateTime? CreatedDate { get; set; }

    [ScaffoldColumn(false)]
    public long? CreatedBy { get; set; }     
}

public class User
{
    [Key]
    public long UserID { get; set; }

    [Required]
    [MaxLength(20)]
    [Display(Name = "User Name")]
    public string UserName { get; set; }
}

【问题讨论】:

    标签: entity-framework orm entity-framework-4.1 foreign-keys


    【解决方案1】:

    您的映射是正确的 - 尤其是 [ForeignKey("CreatedBy")] 属性,您无需更改任何内容。

    在实体框架中的外键关系中,依赖 (= Post) 及其外键始终引用主体的主键 (= User) - 并且主键是 UserID - 按照惯例还因为您已使用 Key 属性对其进行了标记。您无需再指定任何内容。

    您的关系是可选的(0..1 对多),因为外键 CreatedBy 可以为空(long?)。因此,数据库中可能存在尚未由任何用户创建的帖子。如果您不希望这样,您可以使用不可为空的外键属性 (long CreatedBy) 来建立所需的关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 2015-03-26
      • 2011-08-25
      • 2015-11-06
      相关资源
      最近更新 更多