我正在使用数据库第一种方法开发实体框架,我遇到了以下问题。
我有一个Customer表,其列为col1,col2,col3,....,col8。我为这个表创建了一个实体,这个表已经有大约100个记录。在大于8列中,col4被标记为非空。
Class Customer
{
member col1;
member col2;
member col3;
member col4;
.
.
member col8;
}
class Main
{
//main logic to read data from database using EF
Customer obj = object of Customerwith values assigned to col1,col2 and col3 members
obj.col2=some changed value.
DBContext.SaveChanges(); //<- throws an error stating it is expecting value of col4.
}
在我的应用程序中,我试图使用EF使用存储过程读取其中一个记录,而存储过程只返回col1,col2和col3。 我试图保存col2的修改值并尝试使用DBContext保存回数据库。但它提供了一个错误,表明未提供所需字段col4的值。
仅供参考:我已经浏览了几个论坛,并且在SaveChanges上使用禁用验证的问题和选项对我来说是不可行的。
有没有其他方法可以实现部分更新?
答案 0 :(得分:1)
我猜EntityFramework.Utilities符合您的条件。
此代码:
using (var db = new YourDbContext())
{
db.AttachAndModify(new BlogPost { ID = postId }).Set(x => x.Reads, 10);
db.SaveChanges();
}
将生成单个SQL命令:
exec sp_executesql N'UPDATE [dbo].[BlogPosts]
SET [Reads] = @0
WHERE ([ID] = @1)
',N'@0 int,@1 int',@0=10,@1=1
答案 1 :(得分:0)
对SaveChanges的禁用验证对我来说是不可行的
当然可以。你甚至有来禁用Save上的验证。但是,你不能将整个实体标记为已修改,我认为你做了。您必须将各个属性标记为已修改:
var mySmallCustomer = someService.GetCustomer(); // from sproc
mySmallCustomer.col2 = "updated";
var myLargeCustomer = new Customer();
context.Customers.Attach(myLargeCustomer);
Entry(myLargeCustomer).CurrentValues.SetValues(mySmallCustomer);
// Here it comes:
Entry(myLargeCustomer).Property(c => c.col2).IsModified = true;
context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();
所以你认为它足以让小&#34;小&#34;顾客。在此对象中,您将创建一个存根实体(myLargeCustomer
),用于更新一个属性。