2017-10-18 55 views
0

我想将currentAppointment复制到约会。我的问题是currentAppointment有一个GUID。当我尝试创建新的重复约会时,出现以下错误。 '属性'AppID'是对象关键信息的一部分,不能修改。 '对象的关键信息,无法修改

这完全有道理,为什么我得到这个错误,我知道我可以绕过它逐场下来匹配起来(32场),但我想知道是否有办法给'任命'一个新的指导,而不是逐场进行。

 Appointment currentAppointment = db.Appointments.Find(id); 

     Appointment appointment = currentAppointment; 

     appointment.AppID = Guid.NewGuid(); (where I get the error since I already have a guid from currentAppointment but would like appointment to have a new one.) 
     appointment.AgentID = 1; 
     appointment.StatusID = 13; 
     db.Appointments.Add(appointment); 
+1

您需要阅读[参考类型](https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/reference-types)(可能还有[值类型](https) ://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/value-types))。你会得到这个错误,因为'appointment'只是一个指向由'currentAppointment'表示的同一个对象的指针,如果你改变了另一个对象。什么是数据库?它是实体框架还是其他? – Equalsk

+0

实体框架 –

+0

您可以考虑使用'AsNoTracking'来完成此操作。 https://stackoverflow.com/questions/15308747/entity-framework-5-deep-copy-clone-of-an-entity –

回答

0

有了这个错误,我认为你的AppID是你的主键。所以如果这是一个主键,你的Guid.NewGuid();可以返回数据库中已有的值。所以你可以将它保存在变量和验证码中,如果存在与该密钥的任何约会,如果不存在,则添加,如果存在,你的车会生成另一个。

1

正如我在评论中提到的,您应该阅读关于Reference Types vs Value Types的内容,以了解为什么会出现此错误。

简而言之,当你说Appointment appointment = currentAppointment;你有点创建一个链接从appointmentcurrentAppointment代表的同一个对象。当你改变一个属性时,它会改变另一个。

实体框架有办法将一个类映射到另一个像这样:

// Get current Appointment 
var currentAppointment = db.Appointments.Find(id); 

// Make a brand new Appointment 
var appointment = new Appointment(); 

// Map one to the other 
db.Entry(currentAppointment).CurrentValues.SetValues(appointment); 

// Change the ID 
appointment.AppID = Guid.NewGuid(); 

// Add to database 
db.Appointments.Add(appointment); 

// Whatever else happens 

// Save 
db.SaveChanges(); 

您可能需要做一些工作,以避免碰撞,因为是一个机会,GUID的任命可能已经存在。

个人而言,我建议让AppId的数据库列设置为生成GUID本身的identifier。然后,您在C#中的对象在添加时只有一个null ID,其余部分在数据库级别完成。

相关问题