I have a user class
public partial class User
{
public User()
{
this.Roles = new HashSet<Role>();
this.Achievements = new HashSet<Achievement>();
this.Games = new HashSet<Game>();
}
public int UserId { get; set; }
public string PhoneId { get; set; }
public string UserName { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual ICollection<Achievement> Achievements { get; set; }
public virtual ICollection<Game> Games { get; set; }
}
and an Achievement class
public partial class Achievement
{
public Achievement()
{
this.Users = new HashSet<User>();
}
public int AchievementId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public byte[] Image { get; set; }
public virtual ICollection<User> Users { get; set; }
}
The two classes have a many to many relationship with each other because one user can have 1 or more achievements and an achievement can exist for 1 or more users. I've created the below method to assign an achievement to a user.
public bool AssignAchievementToUser(string userId, int AchievementId)
{
try
{
Context db = new Context();
User user = db.Users.SingleOrDefault(p => p.userId== userId);
Achievement ach = db.Achievements.SingleOrDefault(p => p.AchievementId == AchievementId);
if (user == null || ach == null)
{
return false;
}
user.Achievements.Add(ach);
db.SaveChanges();
return true;
}
catch (Exception e)
{
return false;
}
}
When I invoke this method I get the following exception.
A first chance exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll
Unable to update the EntitySet 'User_X_Achievements' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at DiServiceLibrary.DiService.AssignAchievementToUser(String UID, Int32 AchievementId) in g:\di\di\DiServiceLibrary\DiService.cs:line 101
How should I assign an achievement to a user?