Asp.net mvc entity framework code first associate foreign key with different name

天大地大妈咪最大 提交于 2019-12-12 03:09:24

问题


How can I associate a foreign key with different names here: createdby in post and UserID in users table.

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

回答1:


Your mapping is correct - especially the [ForeignKey("CreatedBy")] attribute, you don't need to change anything.

In a foreign key relationship in Entity Framework the dependent (= Post) and its foreign key always refers to the primary key of the principal (= User) - and the primary key is UserID - by convention and also because you have marked it with the Key attribute. There is nothing you need to specify anymore.

Your relationship is optional (0..1-to-many) because the foreign key CreatedBy is nullable (long?). So there can be posts in the database which haven't been created by any user. If you don't want this, you can make the relationship required by using a non-nullable foreign key property (long CreatedBy).



来源:https://stackoverflow.com/questions/10258088/asp-net-mvc-entity-framework-code-first-associate-foreign-key-with-different-nam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!