Asp.net mvc entity framework code first associate

2019-09-05 16:59发布

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条回答
祖国的老花朵
2楼-- · 2019-09-05 17:47

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).

查看更多
登录 后发表回答