I have following Models:
public class DivorceCases
{
[Key]
[Required]
public string case_id { get; set; }
public string archived { get; set; }
public virtual Plaintiff p { get; set; }
}
public class Plaintiff{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public string name { get; set; }
}
I am having a ModelView of DivorceCases for editing and in controller, I am using:
DivorceCases dcold = db.DivorceCase.Where(x => x.case_id == dc.case_id).Include(x => x.p).SingleOrDefault();
dcold.p = dc.p;
db.Entry(dcold).State = EntityState.Modified;
db.SaveChanges();
When I update, instead of Updating the existing entry in Plaintiffs table, the EF6 inserts a new record in Plaintiffs table and updates the foreign key reference for this new record in DivorceCases table. What am I doing wrong? How do I get rid of that?
I got a solution after repeated debugging and hit and trials.
First of all I made a DBContextExtension Class like this:
public static T Modify<T>(this T t,T tnew)
{
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.Name != "id" && (property.PropertyType==typeof(string) || property.PropertyType==typeof(DateTime)))
{
if (property.GetValue(tnew) != null)
property.SetValue(t, property.GetValue(tnew));
}
}
return t;
}
Then for each foreign key referenced object, I called this Extension method and got 100% success.
DivorceCases dcold = db.DivorceCase.Where(x => x.case_id == dc.case_id).Include(x => x.p).SingleOrDefault();
dcold = dcold.Modify(dc);
dcold.p = dcold.p.Modify(dc.p);
dcold.d = dcold.d.Modify(dc.d);
db.SaveChanges();