使用ID与对象的EF外键引用 [英] EF foreign key reference using Id vs object

查看:102
本文介绍了使用ID与对象的EF外键引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ID与对象的外键引用之间有什么区别。

What is the difference between foreign key reference using Id vs object.

例如:
使用ID的FK关系

For example: FK relation using Id

class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string PhoneNumber { get; set; }

    public int CategoryId { get; set; }
}

vs
使用对象的FK关系

vs FK relation using object

class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string PhoneNumber { get; set; }

    public Category Category { get; set; }
}

我从数据库中注意到,通过使用Id属性,该列实际上变为非列-null字段。

I have noticed from database that by using Id property the column essentially becomes non-null field.

这是唯一的区别吗?
我认为我们不能一次查询多个表,即查询相关数据吗?

Is that the only difference? I think we can't query multiple tables at once i.e.querying related data?

我什么时候应该选择使用这两个选项?

When should I choose to use either options?

推荐答案

在第一个示例中,您没有添加关系,只是添加了一个名为CategoryId的整数属性。
在您的第二个示例中,Entity Framework将创建一个名为 Category_ID的整数列,但是您将无法在模型中看到此属性,因此我想显式地添加它自己并可以使用

In your first example you're not adding a relationship, just an integer property named CategoryId. In your second example, Entity Framework will create an integer column named "Category_ID", but you will be not be able to see this property in your model, so I like to explicitly add it my self and be able to use it along with the navigation property.

class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string PhoneNumber { get; set; }


    [ForeignKey("Category")]
    public int CategoryId { get; set; }
    public Category Category{get;set;}
}

这种方式您还可以控制CategoryId的数据类型,因此可以使其成为可选(可空)

This way you can also control the data type of CategoryId, so you could make it optional (nullable)

public int? CategoryId { get; set; }

*不需要外键数据注释,除非您具有执行此操作的属性或导航属性名称不遵循外键属性名称的命名约定(感谢Bardr)

*The foreign key data annotation is not needed, unless you have property or navigation property names that do not follow the naming convention for foreign key property names (thanks Bardr)

这意味着您正在使用产品和类别创建一对多关系(1- *) ,因此在您的Category类中,您将为产品添加集合导航属性

This implies that you're creating a 1 to many relationship (1-*) with products and categories, so in your Category class you would be adding a collection navigation property for products

class Category
{
  public int Id{ get; set;}
  public string Name{ get; set; }
  ...
  public ICollection<Product> Products{get; set;}
}

这篇关于使用ID与对象的EF外键引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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