c# - 如何生成具有多个集合的表的 Controller ?

标签 c# asp.net-mvc asp.net-mvc-5

这是我的表结构和上下文:

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 时,它显示以下错误消息。任何帮助,将不胜感激。 :)

enter image description here

最佳答案

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/

相关文章:

c# - Http POST 方法有时会转到 test.com 而不是 localhost

c# - 可移植类库 HttpClient

c# - JavaScriptSerializer 可以排除具有空值/默认值的属性吗?

c# - 使用 asp.net mvc 为不同的用户类型提供不同的启动布局

c# - ASP.NET MVC5 删除 API 错误的 html 响应

javascript - 如何在 MVC5 View 模板中将值传递给 javascript?

c# - 列表 asp.net 身份中用户的角色名称

c# - 从 Parallel.ForEach 抛出时未处理的 OperationCanceledException

带有文件类型和文本的表单上的 C# asp.net 问题

c# - MVC 防止图像文件的 URL 操作攻击