Reputation: 105
I have a table:
public class TestModel
{
public int Id { get; set; }
public string UserId { get; set; }
public string Name { get; set; }
}
I want UserId column to be a foreign key, Mvc Membership's User's Id column. How can I achive this?
My IdentityModels:
public class ApplicationUser : IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
Upvotes: 10
Views: 11781
Reputation: 1
You might run into error CS1061 when scaffold using Visual Studio 2015, Ater following the great answer : /*************************/
public class TestModel
{
public int Id { get; set; }
public string Name { get; set; }
public string UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser User { get; set; }
}
Add the new model to your DbContext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<TestModel> TestModels { get; set; }
/* rest of class */
}
/*****************************/ Solution Delete the controller and views of the affected controller, Rename to in DbContext to look like this
public class ApplicationDbContext : IdentityDbContext<Users>
Restart VS, then scaffold.
Disclaimer: Am not the author of above solution just edited and posted for someone' benefit
Upvotes: -1
Reputation: 15555
I don't like the idea of using [ForeignKey]
attribute in TestModel
. It's better to do this using Fluent API. Here is the code to add UserId
column in TestModel
table and add a Foreign Key constraint:
public class TestModel
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class ApplicationUser : IdentityUser
{
public virtual TestModel TestModel { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection")
{
}
public DbSet<TestModel> TestModels { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ApplicationUser>()
.HasOptional(m => m.TestModel)
.WithRequired(m => m.ApplicationUser)
.Map(p => p.MapKey("UserId"));
}
}
Upvotes: 0
Reputation: 101604
Add a reference to the ApplicationUser
and specify the ForeignKey:
public class TestModel
{
public int Id { get; set; }
public string Name { get; set; }
public string UserId { get; set; }
[ForeignKey("UserId")]
public ApplicationUser User { get; set; }
}
Add the new model to your DbContext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<TestModel> TestModels { get; set; }
/* rest of class */
}
And you should be good-to-go (less migrations/database updates).
Upvotes: 21