我有一个用户类
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; }
}
和成就班
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; }
}
这两个类之间存在多对多关系,因为一个用户可以拥有 1 个或多个成就,而一个成就可以存在于 1 个或多个用户。我创建了以下方法来将成就分配给用户。
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;
}
}
当我调用此方法时,我得到以下异常。
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
我应该如何将成就分配给用户?