【发布时间】:2014-09-16 01:41:15
【问题描述】:
我遇到了我认为实体框架的一个非常奇怪的情况。基本上,如果我直接使用 sql 命令更新一行,当我通过 linq 检索该行时,它没有更新的信息。有关详细信息,请参阅下面的示例。
首先我创建了一个简单的数据库表
CREATE TABLE dbo.Foo (
Id int NOT NULL PRIMARY KEY IDENTITY(1,1),
Name varchar(50) NULL
)
然后我创建了一个控制台应用程序来将一个对象添加到数据库中,使用 sql 命令对其进行更新,然后检索刚刚创建的对象。这里是:
public class FooContext : DbContext
{
public FooContext() : base("FooConnectionString")
{
}
public IDbSet<Foo> Foo { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Foo>().ToTable("Foo");
base.OnModelCreating(modelBuilder);
}
}
public class Foo
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
static void Main(string[] args)
{
//setup the context
var context = new FooContext();
//add the row
var foo = new Foo()
{
Name = "Before"
};
context.Foo.Add(foo);
context.SaveChanges();
//update the name
context.Database.ExecuteSqlCommand("UPDATE Foo Set Name = 'After' WHERE Id = " + foo.Id);
//get the new foo
var newFoo = context.Foo.FirstOrDefault(x => x.Id == foo.Id);
//I would expect the name to be 'After' but it is 'Before'
Console.WriteLine(string.Format("The new name is: {0}", newFoo.Name));
Console.ReadLine();
}
}
底部的写入行打印出“之前”,但我希望它打印出“之后”。奇怪的是,如果我运行分析器,我会看到 sql 查询运行,如果我自己在管理工作室中运行查询,它会返回“After”作为名称。我正在运行 sql server 2014。
有人可以帮我理解这里发生了什么吗?
更新:
它将转到 FirstOrDefault 行上的数据库。请参阅 sql profiler 的附加屏幕截图。
所以我的问题真的是这样的:
1) 如果它正在缓存,它不应该不去数据库吗?这是 EF 中的错误吗?
2) 如果它要去数据库并消耗资源,EF 不应该更新对象。
【问题讨论】:
标签: c# linq entity-framework entity-framework-6