什么时候在实体框架6中不需要声明关系? [英] When declaring relationship is not necessary in Entity Framework 6?

查看:89
本文介绍了什么时候在实体框架6中不需要声明关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在EF6中,我们有两种方法来声明两个表之间的关系:

In EF6 we have two ways to declare relationship between two tables:

  • 注释属性

  • Annotations Attributes

Fluent API

Fluent API

今天(偶然),我删除了两个表之间的一种关系,并且一切正常.我很惊讶,因为EF没有办法知道这两个表是如何连接的.

Today (by accident) I removed one relationship between two tables and everything kept working well. I was very surprised because there was no way EF would know how those two tables are connected.

表格如下:

[Table("item")]
public class Item
{
    public Item()
    {
        ItemNotes = new HashSet<ItemNote>();
    }
    [Key]
    [Column("itemID", TypeName = "int")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int itemID { get; set; }

    public ICollection<ItemNote> ItemNotes { get; set; }
}

[Table("itemNotes")]
public class ItemNote
{
    [Key]
    [Column("id", TypeName = "int")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Column("itemID", TypeName = "int")]
    public int ItemId { get; set; }
    [Column("note", TypeName = "varchar")]
    [MaxLength(255)]
    public string Note { get; set; }
}    

流利的API:

public class MyContext : DbContext
{
    public MyContext()
        : base("name=MyContext")
    {
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer<MyContext>(null);

        //I removed this relationship:
        //modelBuilder.Entity<Item>().HasMany(i => i.ItemNotes).WithRequired().HasForeignKey(i => i.ItemId);

        base.OnModelCreating(modelBuilder);
    }    
}

这是我进行的测试:这是一个集成测试,它连接到真实数据库,获取带有注释的项目并测试EF:

Here is the test I made: It's an integration test, that connects to the real database, gets items with notes and tests the EF:

    [TestCase]
    public void QueryItemWithItemNotesTest()
    {
        FniContext fniContext = new FniContext();

        int itemId = fniContext.Database.SqlQuery<int>("SELECT TOP(1) itemId FROM item WHERE itemId IN (SELECT itemId FROM dbo.itemNotes)").FirstOrDefault();
        var item = fniContext.Items.AsNoTracking()
            .Include(i => i.ItemNotes)
            .Where(i => i.itemID == itemId).FirstOrDefault();

        Assert.IsNotNull(item);
        Assert.Greater(item.ItemNotes.Count, 0);
    } 

通过!它加载所有笔记! 怎么来?!

It passes! It loads all notes! How come?!

我一直在调查,结果发现在1:1的关系中,我完全不必在代码中有任何关系.我唯一需要的时间是1:1关系.我在想什么吗?大多数关系都是1:1:1,这是否意味着大多数时候1:1就使用了Fluent API?

I kept investigating and it turned out that in case of 1:many relationship I totally don't have to have any relationship in the code. The only time I need it is with 1:1 relationship. Am I'm missing something? Most of relationships are 1:many, so does it mean Fluent API is used for 1:1 most of the time?

推荐答案

实体框架具有一些不需要显式定义的约定.

Entity Framework has some conventions that you do not need to define explicitly.

来自 https://msdn .microsoft.com/en-us/library/jj679962(v = vs.113).aspx#Anchor_2

除了导航属性外,我们建议您还包括 代表相关对象的类型上的外键属性. 与主主键具有相同数据类型的任何属性 属性,其名称遵循以下格式之一 代表关系的外键:'<导航属性 name><主要主键属性名称>','<主要类 name><主键属性名称>'或'<主要主键属性 名称>'.如果找到多个匹配项,则在 上面列出的订单.外键检测不区分大小写.什么时候 检测到外键属性,代码优先"推断多重性 关系基于外键的可为空性.如果 该属性为空,然后将该关系注册为 选修的;否则,将根据需要注册该关系.

In addition to navigation properties, we recommend that you include foreign key properties on the types that represent dependent objects. Any property with the same data type as the principal primary key property and with a name that follows one of the following formats represents a foreign key for the relationship: '<navigation property name><principal primary key property name>', '<principal class name><primary key property name>', or '<principal primary key property name>'. If multiple matches are found then precedence is given in the order listed above. Foreign key detection is not case sensitive. When a foreign key property is detected, Code First infers the multiplicity of the relationship based on the nullability of the foreign key. If the property is nullable then the relationship is registered as optional; otherwise the relationship is registered as required.

这篇关于什么时候在实体框架6中不需要声明关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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