Mic*_* D. 2 entity-framework code-first
我正在尝试使用EF5 CodeFirst而无法使用简单的设置;(
我有两个类Foo和Bar,其中Bar表示查找表.
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Bar Bar { get; set; }
}
public class Bar
{
public int Id { get; set; }
public string Description { get; set; }
}
public class MyDbContext : DbContext
{
static MyDbContext()
{
Database.SetInitializer<MyDbContext>(null);
}
public MyDbContext(): base("testEF"){}
public DbSet<Foo> Foos { get; set; }
public DbSet<Bar> Bars { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在我创建了一个静态类,用作DataAccess Layer - 在实际应用程序中,它将位于不同的物理层
public static class DataAccess
{
public static Bar GetBarById(int id)
{
using (var db = new MyDbContext())
{
return db.Bars.SingleOrDefault(b => b.Id == id);
}
}
public static Foo InsertFoo(Foo foo)
{
using (var db = new MyDbContext())
{
db.Foos.Add(foo);
db.SaveChanges();
}
return foo;
}
}
Run Code Online (Sandbox Code Playgroud)
我用种子方法初始化DB:
internal sealed class Configuration : DbMigrationsConfiguration<testEF.MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(testEF.MyDbContext context)
{
context.Bars.AddOrUpdate(
new Bar { Description = "Bar_1" },
new Bar { Description = "Bar_2" }
);
}
}
Run Code Online (Sandbox Code Playgroud)
这会在Bars表中创建两个记录.到现在为止还挺好...
这是我的主要功能
static void Main(string[] args)
{
var bar1 = DataAccess.GetBarById(1);
var foo = new Foo
{
Name = "Foo_1",
Bar = bar1
};
DataAccess.InsertFoo(foo);
}
Run Code Online (Sandbox Code Playgroud)
应用程序符文后,Foos表中有一条记录:
Id Name Bar_Id
1 Foo_1 3
Run Code Online (Sandbox Code Playgroud)
为什么Bar_Id是3?EF实际上将新记录插入到Bars表中!
Id Description
1 Bar_1
2 Bar_2
3 Bar_1
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
更新: 我找到了一个解决方法 - 在插入记录之前附加Bar属性:
public static Foo InsertFoo(Foo foo)
{
using (var db = new MyDbContext())
{
db.Bars.Attach(foo.Bar);
db.Foos.Add(foo);
db.SaveChanges();
}
return foo;
}
Run Code Online (Sandbox Code Playgroud)
它现在正在工作,但这更像是一个黑客而不是一个有效的解决方案......在实际应用中,对象的复杂性可能成为一个巨大的问题.我愿意接受更好的解决方案
问题是bar1来自不同的数据上下文.您的InsertFoo方法通过与之建立关系隐式地将其添加到第二个上下文Foo.您希望这两者共享一个上下文.因此,对于整个Main方法范围使用单个上下文.
| 归档时间: |
|
| 查看次数: |
1730 次 |
| 最近记录: |