0

ユーザークラスがあります

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 つ以上のアチーブメントを持つことができ、アチーブメントが 1 つ以上のユーザーに対して存在する可能性があるため、2 つのクラスは互いに多対多の関係にあります。以下のメソッドを作成して、実績をユーザーに割り当てました。

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

実績をユーザーに割り当てるにはどうすればよいですか?

4

0 に答える 0