这是我的表结构和上下文:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace AspnetIdentitySample.Models
{
public class Employee : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<MyTask> MyTasks { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
public class MyTask
{
public int MyTaskId { get; set; }
public string Description { get; set; }
public DateTime OldDate { get; set; }
public DateTime NewDate { get; set; }
public bool IsDone { get; set; }
public virtual Employee User { get; set; }
}
public class Customer
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Employee Employee { get; set; }
}
public class MyDbContext : IdentityDbContext<Employee>
{
public MyDbContext()
: base("DefaultConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Change the admin of the table to be Users instead of AspNetUsers
modelBuilder.Entity<IdentityUser>()
.ToTable("Employee");
modelBuilder.Entity<Employee>()
.ToTable("Employee");
}
public DbSet<MyTask> MyTasks { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Employee> Employees { get; set; }
}
}
当我尝试使用 Entity Framework 创建 CRUD Controller 时,它显示以下错误消息。任何帮助,将不胜感激。 :)
最佳答案
OP 添加了更多细节和代码。原始答案已过时且错误
/编辑:
您正试图将 2 个模型绑定(bind)到同一个表:
modelBuilder.Entity<IdentityUser>()
.ToTable("Employee");
modelBuilder.Entity<Employee>()
.ToTable("Employee");
此外,您尝试添加 public DbSet<Employee> Employees { get; set; }
它应该已经在 datsabase 中作为上下文类定义定义的身份表。
我没有尝试重命名 aspnetusers 表,但我会尝试删除以下行:
modelBuilder.Entity<IdentityUser>()
.ToTable("Employee");
public DbSet<Employee> Employees { get; set; }
这应该可以解决问题。
关于c# - 如何生成具有多个集合的表的 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22193293/