Reputation: 4239
I am using Entity Framework 6 with Code First.
Model:
public class UserProfile
{
[Key]
public Guid UserID { get; set; }
public Language PreferredLang { get; set; }
//more properties
}
UserProfile
table is generated with PreferredLang_LanguageID
column. I wrote following method to save user profile. If this UserID is found in DB, I update, otherwise I add row.
public static void UpdateProfile(UserProfile userProfile)
{
using (var db = new Context())
{
if (db.UserProfiles.Any(p => p.UserID == userProfile.UserID))
{
//does not save language properly
db.UserProfiles.Attach(userProfile);
db.Entry(userProfile).State = System.Data.Entity.EntityState.Modified;
db.Entry(userProfile.PreferredLang).State = System.Data.Entity.EntityState.Modified;
}
else
{
//duplicates language
db.UserProfiles.Add(userProfile);
}
db.SaveChanges();
}
}
There are two problems.
When I create new UserProfile (db.UserProfiles.Add), new entry for Language is created, even though Language already existed. PreferredLanguage had ID = 2, and after db.SaveChanges
, it created new Language with ID = 5 (smallest available) and set PreferredLang_LanguageID = 5
. How can I use existing Language?
When I update existing UserProfile, then all properties (columns) are updated in DB, except for `PreferredLang_LanguageID
. This one stays the same. How could Language be updated?
Upvotes: 1
Views: 262
Reputation: 4239
I know that this is not the most elegant solution, but it's the only one that worked for me. If existing entry is found, then it is removed and new instance is attached to context:
if (db.UserProfiles.Any(p => p.UserID == userProfile.UserID))
{
//not elegant, but only solution that works
db.UserProfiles.Remove(db.UserProfiles.Find(userProfile.UserID));
}
db.UserProfiles.Add(userProfile);
db.Languages.Attach(userProfile.PreferredLang);
db.SaveChanges();
Upvotes: 0
Reputation: 4239
To answer first part of question - saving without creating new entry for Language. I attached PreferredLang
:
{
db.UserProfiles.Add(userProfile);
db.Languages.Attach(userProfile.PreferredLang);
}
db.SaveChanges();
Upvotes: 1