EF Repository Update

问题描述:


解决办法:


http://www.cnblogs.com/scy251147/p/3688844.html

原理:


Attaching an entity of type '' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

Entity Framework Core (EF Core) 中,要将属性的值更新为 NULL,你可以将属性的值设置为 null,并将实体状态标记为已修改。当你调用 `SaveChanges` 方法时,EF Core 将会将这些更改应用到数据库。 以下是一个示例,展示了如何使用 EF Core 更新属性的值为 NULL: ```csharp using Microsoft.EntityFrameworkCore; using System; // 创建 DbContext 类 public class YourDbContext : DbContext { public YourDbContext(DbContextOptions<YourDbContext> options) : base(options) { } // DbSet 和其他属性... public DbSet<IPS_Invoice> IPS_Invoices { get; set; } } public class IPS_Invoice { public int IPS_ID { get; set; } public bool BLOCK { get; set; } public DateTime? BLOCKTIME { get; set; } } public class YourRepository { private readonly YourDbContext _dbContext; public YourRepository(YourDbContext dbContext) { _dbContext = dbContext; } public string UpdateBlockTimeToNull(int ipsId) { string message = ""; try { var invoice = _dbContext.IPS_Invoices.Find(ipsId); if (invoice != null) { invoice.BLOCKTIME = null; _dbContext.Entry(invoice).State = EntityState.Modified; _dbContext.SaveChanges(); message = "Update successful"; } else { message = "Invoice not found"; } } catch (Exception e) { message = "Update failed"; // 处理异常... } return message; } } ``` 在上述代码中,我们首先创建了一个继承自 `DbContext` 的 `YourDbContext` 类,并定义了需要操作的实体类 `IPS_Invoice`。然后,我们创建了一个名为 `YourRepository` 的仓储类,在该类中使用 `Find` 方法查找要更新的实体对象。 在 `UpdateBlockTimeToNull` 方法中,我们将 `BLOCKTIME` 属性的值设置为 null,并将实体状态标记为已修改。然后,调用 `SaveChanges` 方法将更改应用到数据库。 请根据你的实际情况修改代码,并确保在使用 EF Core 时按照最佳实践进行数据库操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值