How do I get save add functionality to work with EF4 when my key field must be unique but I set it during the web session?
Here is the two important bits. I have a taxpayerID that comes from the Current users profile, but then I want to move that value from the ASPNETDB database into my actual transaction database, so I know the value, but this code fails. It will insert the first time and fail on every following save,
{"A duplicate value cannot be inserted into a unique index. [ Table name = dr405,Constraint name = PK_dr405_0000000000000072 ]"}
I've tried deleting the database to clear out any cobwebs and that did not seem to help.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public String TaxPayerID { get; set; }
public DateTime CreateDate { get; set; }
开发者_如何学JAVApublic void Save(DR405DBContext context, dr405 obj)
{
if (obj.CreateDate == null)
{
obj.CreateDate = DateTime.Now;
}
obj.ModDate = DateTime.Now;
context.Entry(obj).State = obj.TaxPayerID == null ? EntityState.Added : EntityState.Modified;
obj.TaxPayerID = Tangible.Profiles.DR405Profile.CurrentUser.TaxPayerID;
context.SaveChanges();
}
According to your error text, you are trying to insert item with existing Primiry key to the table.
Check the State
property of your object. It seems that it always EntityState.Added
Did you check the value: Tangible.Profiles.DR405Profile.CurrentUser.TaxPayerID
Since you reset your TaxPayerId
before you save. looks for me that error comes from here.
I really appreciate everyones responses. I solved the issue by using third example in the accepted answer is the trick. stackoverflow.com/questions/5557829/…
I was having problems due to a general lack of knowledge about EF4 and the way it tracks changes.
精彩评论