Asp.net mvc实体框架代码首先将外键与不同的名称相关联 [英] Asp.net mvc entity framework code first associate foreign key with different name

查看:112
本文介绍了Asp.net mvc实体框架代码首先将外键与不同的名称相关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将外键与不同的名称相关联:在用户表中的帖子和 UserID 中创建

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


推荐答案

您的映射是正确的 - 特别是 [ForeignKey(CreatedBy)] 属性,您不需要更改任何内容。

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

实体框架中的外键关系依赖(= Post )及其外键总是引用主键的主键(= User ) - 并且主键是 UserID - 按照惯例,还因为您已经使用键标记属性。没有什么需要指定的。

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.

您的关系是可选的(0..1对多),因为外键 CreatedBy 是可空的( long?)。所以在数据库中可以有没有任何用户创建的帖子。如果你不想要这个,你可以使用不可空的外键属性( long CreatedBy )来实现关系。

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

这篇关于Asp.net mvc实体框架代码首先将外键与不同的名称相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆