实体框架4-并非始终使用ApplyCurrentValues更新布尔属性 [英] Entity Framework 4 - Not always updating boolean property using ApplyCurrentValues
问题描述
我有一个简单的国家/地区实体,由Entity Framework 4使用VS 2010 RC制作。
公共类公司
{
public int ID {get;组; }
公共字符串Name {get;组; }
公用字串ISOCode {get;组; }
public boolean Active {get;组; }
}
我的存储库代码如下。 db是在构造函数中初始化的我的上下文。
public void EditCountry(Country countryToEdit)
{
db.Countries.Attach(新国家/地区{ID = countryToEdit.ID});
db.Countries.ApplyCurrentValues(countryToEdit);
db.SaveChanges();
}
在countryToEdit中将Active字段从false更改为true会产生以下SQL
更新[dbo]。[国家/地区]
set [名称] = @ 0,[ISOCode] = @ 1,[有效] = @ 2
其中([ID] = @ 3)
@ 0 nvarchar(256),@ 1 nvarchar(12),@ 2位,@ 3 int,@ 0 ='阿尔及利亚' ,@ 1 ='DZ',@ 2 = 1,@ 3 = 4
这是预期的。
如果我在countryToEdit中将活动字段从true更改为false,则会生成以下SQL
更新[dbo]。[国家/地区]
set [名称] = @ 0,[ISOCode] = @ 1
其中([ID] = @ 2)
@ 0 nvarchar(256),@ 1 nvarchar(12),@ 2 int,@ 0 ='Afghanistann',@ 1 ='AF',@ 2 = 1
没有尝试更新活动字段。
这个在EF 4中的ApplylyValues 问题具有答案。
应该是
db.Countries.Attach(db.Countries.Single(c => c.ID == countryToEdit.ID));
如果附加空白存根对象,则布尔字段将初始化为false。
上面的代码添加了另一个数据库查询,但是我可以接受。
ApplyCurrentValues调用看不到存根和已编辑对象之间的布尔值没有变化。
p>I have a simple entity for a Country that is produced by Entity Framework 4 using VS 2010 RC. It looks something like the POCO below.
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public string ISOCode { get; set; }
public boolean Active { get; set; }
}
My repository code is below. 'db' is a my context that is initialized in the constructor.
public void EditCountry(Country countryToEdit)
{
db.Countries.Attach(new Country { ID = countryToEdit.ID });
db.Countries.ApplyCurrentValues(countryToEdit);
db.SaveChanges();
}
Changing the Active field from false to true in countryToEdit produces the following SQL
update [dbo].[Countries]
set [Name] = @0, [ISOCode] = @1, [Active] = @2
where ([ID] = @3)
@0 nvarchar(256),@1 nvarchar(12),@2 bit,@3 int,@0='Algeria',@1='DZ',@2=1,@3=4
This is expected.
If I change the Active field from true to false in countryToEdit the following SQL is produced
update [dbo].[Countries]
set [Name] = @0, [ISOCode] = @1
where ([ID] = @2)
@0 nvarchar(256),@1 nvarchar(12),@2 int,@0='Afghanistann',@1='AF',@2=1
There is no attempt made to update the Active field.
This ApplyCurrentValues in EF 4 question has the answer.
It should be
db.Countries.Attach(db.Countries.Single(c => c.ID == countryToEdit.ID));
If you attach a blank stub object the boolean fields are initialised to false. The ApplyCurrentValues call sees no change in the boolean value between the stub and the editied object.
The code above adds another DB query, but I can live with that.
这篇关于实体框架4-并非始终使用ApplyCurrentValues更新布尔属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!