2

認証方法として組み込みのMVCユーザープロファイルを使用する基本的なWebサイトを作成しようとしています。私はMVC4.0とEntityFrameworkを使用しています。

UserProfileモデルを外部キーとして使用するメインデータクラスがあります。このクラスは、ゲームを特定のユーザーに関連付けることを目的とした「ゲーム」クラスです。

このプロジェクトの必要性として、UserProfileクラスに別のメンバーも追加しました。

ユーザーのプロファイルが外部キーとして含まれている新しいゲームを追加しようとするたびに、サーバーは、同じユーザーになるように特別に作成したにもかかわらず、まったく新しいユーザープロファイルを作成することになります。

この問題を修正する試みの一環として、ゲームオブジェクトをユーザープロファイルDbContextに追加しましたが、これはまったく役に立ちませんでした。データベースに新しいゲームを挿入するたびに、新しいユーザーを作成します。

私のモデルは次のとおりです。

public class Game
{
    public int ID { get; set; }

    [ForeignKey("UserId")]
    public virtual UserProfile Profile { get; set; }

    public int UserId { get; set; }
}

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    public int Balance { get; set; }
}

私の新しいUsersContextは次のとおりです。

public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Game> GamesList { get; set; }
}

新しいゲームを追加するための私の方法は次のとおりです。

        Models.UsersContext uc = new UsersContext();
        UserProfile prof = uc.UserProfiles.Where(c=>c.UserName == HttpContext.User.Identity.Name).First();
        Game g = new Game();
        g.Profile = prof;
        g.Wager = int.Parse(BetQuantity);

        uc.GamesList.Add(g);
        uc.SaveChanges();

私は自分が何を間違っているのか本当にわかりません。どんな助けでも大歓迎です!

4

1 に答える 1