带外键的实体框架 [英] Entity Framework with foreign keys

查看:94
本文介绍了带外键的实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,实体框架应该如何与相关表一起使用。

In short how is Entity Framework suppose to work with related tables.

aspnetcore 2.0

aspnetcore 2.0

public class Table1{
    [Key]
    public int Id{get;set;}

    [ForeignKey("Table2")]
    public int Table2Id {get;set;}
    public virtual Table2 Table2{get;set;}
}

public class Table2{
    [Key]
    public int Id{get;set;}

}

I假定使用以下语句

var t1 = context.Table1List.FirstOrDefault( j => j.Id == 1)

将自动填充Table2,但t1.Table2为空。

would have automatically populated Table2 but t1.Table2 is null.

如果我要调用context.Table2List.FirstOrDe .....则即使未设置属性也将填充t1.Table2。因此,EF认识到只有在我物理上向数据库发出呼叫之后,这种关系才开始填充。

If I was to call context.Table2List.FirstOrDe..... then t1.Table2 is populated even without setting the property. So EF recognizes the relationship just does not populate until I physically make the call to the DB.

我是不是对EF如何工作有误,或者仅仅是一个错误而了解在我的代码中。也许与延迟加载有关。

Is my understanding of how EF is suppose to work wrong or is just an error in my code. Maybe something to do with lazyloading.

我已经阅读并阅读了Microsoft的教程,但对它的工作原理和实际工作却知之甚少。

I have read and read and read Microsofts tutorials but with no much understanding how it is Suppose to work versus how it actually works.

表1和表2之间只有一对一的关系。

Table 1 and 2 only have a one to one relationship with each other.

推荐答案

更新:

您必须更改模型,例如:

You have to change your model like:

public class Table1{
    public int Id{get; set;} //Primary key by convention
    [ForeignKey("Table2")]
    public int Table2Id{get; set;}
    public virtual Table2 Table2{get; set;}
}

public class Table2{
    public int Id{get; set;} //Primary key by convention
    public virtual Table1 Table1{get; set;}
}

在您的上下文中,您必须设置以下内容:

And in you context you have to set this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure table1 & table2 entity
    modelBuilder.Entity<Table2>()
                .HasOptional(s => s.Table1) // Mark Table1 property optional in Table2 entity
                .WithRequired(ad => ad.Table2); // mark Table1 property as required in Table2 entity. Cannot save Table1 without Table
}

无法保存Table1,当您要从一个表中获取数据时,还从相关表中获取数据,您在查询中使用了 Include 方法,例如:

And when you want to get data from one table, also get data from related table, you have using Include method in you query like:

var result  = var t1 = context.Table1List.Include(x=>x.Table2).FirstOrDefault( j => j.Id == 1);

使用此代码,您可以获得有关相关表的数据。

with this code, you have data about related table.

如果您愿意,我可以为您创建更多示例。

if you want, I can create more sample for you.

这篇关于带外键的实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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