Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing UserProfile foreign key in class creates new profiles in MVC 4
    primarykey
    data
    text
    <p>I'm trying to make a basic website that uses the built in MVC user profile as the authentication method. I'm using MVC4.0 and Entity Framework.</p> <p>I have a main data class that uses the UserProfile model as a foreign key. This class is a "game" class, for the purpose of relating a game to a certain user.</p> <p>I've also added another member to the UserProfile class, as a necessity for this project.</p> <p>Every time I try to add a new game, which has a user's profile in it as a foreign key, the server ends up making a new user profile altogether, even though I specifically made it so that it's the same user.</p> <p>As a part of an attempt to fix this issue, I added the Game object to the user profile DbContext, this didn't help at all, however, and I still create new users every time I insert a new game to the database.</p> <p>My models are as follow:</p> <pre><code>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; } } </code></pre> <p>My new UsersContext is:</p> <pre><code>public class UsersContext : DbContext { public UsersContext() : base("DefaultConnection") { } public DbSet&lt;UserProfile&gt; UserProfiles { get; set; } public DbSet&lt;Game&gt; GamesList { get; set; } } </code></pre> <p>My method for adding a new game is:</p> <pre><code> Models.UsersContext uc = new UsersContext(); UserProfile prof = uc.UserProfiles.Where(c=&gt;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(); </code></pre> <p>I really have no idea what I'm doing wrong, any help would be enormously appreciated!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload