I'm using the Entity Framework v4 for a small project. Normally I use NHibernate. My issue is that I accidentally had code which added an object which was already persisted to the DB Context's collection, and when开发者_如何学JAVA I did a SaveChanges(), the EF made a copy of the object, giving it a new Primary Key.
While this is useful, it's not what I wanted. Is there a way to turn off that functionality, and instead have an exception thrown?
UPDATE: CODE NOW INCLUDED
public class CcUser
{
public int Id { get; set; }
[StringLength(50)]
public string TrackingId { get; set; }
[StringLength(50)]
public string MembershipGuid { get; set; }
public bool CookiesConfirmed { get; set; }
[StringLength(200)]
public string Email { get; set; }
public DateTime Modified { get; set; }
}
public class MyDbContext : DbContext
{
public DbSet<CcUser> Users { get; set; }
}
MyDbContext db = new MyDbContext();
var ccUser = db.Users.FirstOrDefault(u => u.TrackingId == id);
ccUser.Modified = DateTime.UtcNow;
db.Users.Add(ccUser);
db.SaveChanges();
How do you know that it was the same object?
For example if it was because it had the same name, then you could add a unique index on the name field. That way adding a duplicate row would throw an exception.
Did you try it without the line to add the ccuser (eg the penultimate line). If the object is already attached to the context, savechanges() should persist the changes. If that doesn't work then try calling detectchanges() before savechanges().
For everyone who run into that problem:
Method .Add
marking entity
with EntityState.Added
. And when you add existent in context item EF would consider it as a new object because of the Lazy Loading.
And afterwards context.SaveChanges()
will generate new primary key for added item and save it to DB
.
Use AddOrUpdate
if you dont need that feature.
Here related question on MSDN
精彩评论