实体框架添加到ICollection

时间:2013-03-14 20:50:02

标签: c# asp.net entity-framework entity-framework-5 ef-database-first

我有一个用户类

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

这两个类彼此之间存在多对多的关系,因为一个用户可以拥有一个或多个成就,并且一个或多个用户可以存在一个成就。我创建了以下方法来为用户分配成就。

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

我应该如何为用户分配成就?

0 个答案:

没有答案