2

我将 EF Code First 与预先存在的数据库一起使用。

两个对象:

public Foo
{
    public int FooId {get;set;}
}

public Bar
{
    public int BarId {get;set;}
    public virtual Foo Foo {get;set;}
}

FooId和都是BarId数据库中的主键,Bar表中有一列FooId是指向Foo表的外键。

当我选择 aBar时,Foo是一个空引用。我原以为EF会自动将它们两个拉到一起,但也许我错过了什么?

数据库映射:

public class EFCodeFirst : DbContext
{
    public EFCodeFirst()
    {
        this.Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["AlternateString"].ConnectionString;
    }

    public DBSet<Foo> Foos {get;set;}
    public DBSet<Bar> Bars {get;set;}

    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        modelBuilder.IncludeMetadataInDatabase = false;
        modelBuilder.Entity<Foo>().MapSingleType().ToTable("Foo");
        modelBuilder.Entity<Bar>().MapSingleType().ToTable("Bar");
    }
}
4

2 回答 2

2

If your expectation of Foo should not be null is coming from the fact that you make it virtual on Bar object, then that's not the case. By make them virtual, you just opt in to EF lazy loading and it will be null up until to the point that you explicitly ask for it by accessing it on Bar object. Other than that, if you want it to be populated upfront you would have to eager load it with Include method.

To explicitly disable lazy loading you can use the following code, even though you don't need it since you can just remove the virtual keyword from your navigation properties and lazy loading would be gone.

public EFCodeFirst()
{        
    this.ObjectContext.ContextOptions.LazyLoadingEnabled = false;
}

Internally, DbContext uses a protected ObjectContext that you can also use inside your inherited DbContext class (e.g. EFCodeFirst).

于 2010-11-19T05:18:25.837 回答
0

You are missing a line in the Foo class, that Foo contains a collection of Bar.

于 2010-11-19T09:41:29.207 回答