带外键的实体框架

时间:2018-10-02 15:23:01

标签: c# entity-framework asp.net-core

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

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

}

我以为

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

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

如果我要调用context.Table2List.FirstOrDe .....,那么即使未设置属性也将填充t1.Table2。因此,EF意识到直到我亲自向数据库发出呼叫后,这种关系才开始出现。

是我对EF如何工作错误的理解,还是仅仅是我的代码中的错误。也许与延迟加载有关。

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

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

3 个答案:

答案 0 :(得分:0)

主要按照惯例进行布线,并假定一对多关系,您是说要制作一组看起来像这样的模型吗?

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

public class Table2
{
    public int Id { get; set; }     //Primary key by convention
    public ICollection<Table1> Table1s { get; set; }
}

答案 1 :(得分:0)

您需要的称为Lazy Loading

通过检查文档记录,您发现必须显式启用延迟加载:

.AddDbContext<BloggingContext>(
    b => b.UseLazyLoadingProxies()
          .UseSqlServer(myConnectionString));

并且您的Table2属性必须为virtual

public class Table1 
{  
    public virtual Table2 Table2{get;set;}
}

您甚至不需要Id外键!

答案 2 :(得分:-1)

更新

您必须像以下那样更改模型

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

在您的情况下,您必须设置以下内容:

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
}

当您要从一个表中获取数据时,也要从相关表中获取数据时,可以在查询中使用Include方法,例如:

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

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

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