1

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; }

public 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();
}
VMAtm
  • 27,943
  • 17
  • 79
  • 125
Doug Chamberlain
  • 11,192
  • 9
  • 51
  • 91
  • The third example in the accepted answer is the trick. http://stackoverflow.com/questions/5557829/update-row-if-it-exists-else-insert-logic-with-entity-framework – Doug Chamberlain Jul 18 '11 at 16:02

3 Answers3

1

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

VMAtm
  • 27,943
  • 17
  • 79
  • 125
1

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.

VMAtm
  • 27,943
  • 17
  • 79
  • 125
John Liu
  • 186
  • 4
0

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.

Community
  • 1
  • 1
Doug Chamberlain
  • 11,192
  • 9
  • 51
  • 91