实体框架添加现有项目导致克隆 [英] Entity Framework Adding Existing Item Causes Clone

查看:61
本文介绍了实体框架添加现有项目导致克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Entity Framework v4用于一个小型项目。通常我使用NHibernate。我的问题是,我不小心有代码添加了一个已经保留在数据库上下文集合中的对象,当我执行SaveChanges()时,EF制作了该对象的副本,并为其赋予了新的主键。

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 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?

更新:现在包含代码

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();


推荐答案

您尝试了没有添加ccuser的行吗? (例如倒数第二行)。如果对象已附加到上下文,则savechanges()应该保留更改。如果这样不起作用,请尝试在savechanges()之前调用detectchanges()。

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().

这篇关于实体框架添加现有项目导致克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆