【问题标题】:Entity Framework Core Code First is not working with existing DatabaseEntity Framework Core Code First 不适用于现有数据库
【发布时间】:2020-09-02 21:27:26
【问题描述】:

我正在关注this 链接以学习和了解 Entity Framework Core 代码优先与 ASP.NET Core MVC 项目中的现有数据库。当然,这里我没有使用 MVC 概念,因为它是基础学习。

我有一个数据库 MyDatabase 有两个表 - DepartmentEmployee

因此,我在Models 文件夹中创建了这个Department 类:

namespace CodeFirstWithExistingDatabase.Models
{
    public class Department
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
    }
}

这是Employee 类:

namespace CodeFirstWithExistingDatabase.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        [DataType(DataType.Currency)]
        public decimal Salary { get; set; }
        public int DepartmentId { get; set; }
    }   
}

下面是DbContext 类:

namespace CodeFirstWithExistingDatabase.Models
{
    public class EFCFWithExistingDBContext : DbContext
    {
        public EFCFWithExistingDBContext(DbContextOptions<EFCFWithExistingDBContext> options) : base(options)
        {
        }

        public DbSet<Department> Departments { get; set; }
        public DbSet<Employee> Employees { get; set; }
    }
}

这就是我将DbContext 添加到Startup.cs 文件中的服务的方式:

services.AddDbContext<EFCFWithExistingDBContext>(x => x.UseSqlServer(Configuration.GetConnectionString("MyDatabaseConnection")));

这是我在appsettings.json文件中声明的连接字符串:

  "ConnectionStrings": {
     "MyDatabaseConnection": "Data Source=.\\SQLEXPRESS;Initial Catalog=MyDatabase;User ID=sa;Password=foobar"
  }

这是HomeController 中的代码,用于测试记录是否来自DepartmentEmployee 表。

namespace CodeFirstWithExistingDatabase.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly EFCFWithExistingDBContext _context;

        public HomeController(ILogger<HomeController> logger, EFCFWithExistingDBContext context)
        {
            _logger = logger;
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        public IActionResult Index()
        {
            var departments = _context.Departments.ToList();
            var employees = _context.Departments.ToList();
            return View();
        }
    }
}

现在,我已经在包管理器控制台中执行了以下命令。

Add-Migration Initial

从生成的Migrations 文件夹中,我刚刚注释掉了Up 方法中的所有代码,如下所示:

protected override void Up(MigrationBuilder migrationBuilder)
{
    //migrationBuilder.CreateTable(
    //    name: "Departments",
    //    columns: table => new
    //    {
    //        Id = table.Column<int>(nullable: false)
    //            .Annotation("SqlServer:Identity", "1, 1"),
    //        Name = table.Column<string>(nullable: true),
    //        Location = table.Column<string>(nullable: true)
    //    },
    //    constraints: table =>
    //    {
    //        table.PrimaryKey("PK_Departments", x => x.Id);
    //    });

    //migrationBuilder.CreateTable(
    //    name: "Employees",
    //    columns: table => new
    //    {
    //        Id = table.Column<int>(nullable: false)
    //            .Annotation("SqlServer:Identity", "1, 1"),
    //        Name = table.Column<string>(nullable: true),
    //        Salary = table.Column<decimal>(nullable: false),
    //        DepartmentId = table.Column<int>(nullable: false)
    //    },
    //    constraints: table =>
    //    {
    //        table.PrimaryKey("PK_Employees", x => x.Id);
    //    });
}

现在,我使用带有-v 标志的Update-Database 命令:

Update-Database -v

这会生成日志:

Using project 'CodeFirstWithExistingDatabase'.
Using startup project 'CodeFirstWithExistingDatabase'.
Build started...
Build succeeded.
C:\Program Files\dotnet\dotnet.exe exec --depsfile F:\Ashok\VS2019\Practice_Web_MVC_WebAPI_NetCore\CodeFirstWithExistingDatabase\bin\Debug\netcoreapp3.1\CodeFirstWithExistingDatabase.deps.json --additionalprobingpath C:\Users\Ashok\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig F:\Ashok\VS2019\Practice_Web_MVC_WebAPI_NetCore\CodeFirstWithExistingDatabase\bin\Debug\netcoreapp3.1\CodeFirstWithExistingDatabase.runtimeconfig.json C:\Users\Ashok\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.7\tools\netcoreapp2.0\any\ef.dll database update --verbose --no-color --prefix-output --assembly F:\Ashok\VS2019\Practice_Web_MVC_WebAPI_NetCore\CodeFirstWithExistingDatabase\bin\Debug\netcoreapp3.1\CodeFirstWithExistingDatabase.dll --startup-assembly F:\Ashok\VS2019\Practice_Web_MVC_WebAPI_NetCore\CodeFirstWithExistingDatabase\bin\Debug\netcoreapp3.1\CodeFirstWithExistingDatabase.dll --project-dir F:\Ashok\VS2019\Practice_Web_MVC_WebAPI_NetCore\CodeFirstWithExistingDatabase\ --language C# --working-dir F:\Ashok\VS2019\Practice_Web_MVC_WebAPI_NetCore --root-namespace CodeFirstWithExistingDatabase
Using assembly 'CodeFirstWithExistingDatabase'.
Using startup assembly 'CodeFirstWithExistingDatabase'.
Using application base 'F:\Ashok\VS2019\Practice_Web_MVC_WebAPI_NetCore\CodeFirstWithExistingDatabase\bin\Debug\netcoreapp3.1'.
Using working directory 'F:\Ashok\VS2019\Practice_Web_MVC_WebAPI_NetCore\CodeFirstWithExistingDatabase'.
Using root namespace 'CodeFirstWithExistingDatabase'.
Using project directory 'F:\Ashok\VS2019\Practice_Web_MVC_WebAPI_NetCore\CodeFirstWithExistingDatabase\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
Using application service provider from Microsoft.Extensions.Hosting.
Found DbContext 'EFCFWithExistingDBContext'.
Finding DbContext classes in the project...
Using context 'EFCFWithExistingDBContext'.
Microsoft.EntityFrameworkCore.Model.Validation[30000]
      No type was specified for the decimal column 'Salary' on entity type 'Employee'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values using 'HasColumnType()'.
Finding design-time services for provider 'Microsoft.EntityFrameworkCore.SqlServer'...
Using design-time services from provider 'Microsoft.EntityFrameworkCore.SqlServer'.
Finding design-time services referenced by assembly 'CodeFirstWithExistingDatabase'.
No referenced design-time services were found.
Finding IDesignTimeServices implementations in assembly 'CodeFirstWithExistingDatabase'...
No design-time services were found.
Done.

当验证生成的日志时,在文件末尾,下面的语句让我很困扰。它能显示对结果的影响吗?

Finding design-time services referenced by assembly 'CodeFirstWithExistingDatabase'.
No referenced design-time services were found.
Finding IDesignTimeServices implementations in assembly 'CodeFirstWithExistingDatabase'...
No design-time services were found.

现在,按 F5 执行项目。但是,我没有从数据库表中获取行。也没有错误。

【问题讨论】:

    标签: c# entity-framework-core


    【解决方案1】:

    我找到了我的问题的解决方案。解析很简单,只需在 Models 文件夹中的类中添加[Table(name)] 属性即可,如下所示。

    namespace CodeFirstWithExistingDatabase.Models
    {
        [Table("Department")] //<--Now, I have added this line of code
        public class Employee
        {
            public int Id { get; set; }
            public string Name { get; set; }
            [DataType(DataType.Currency)]
            public decimal Salary { get; set; }
            public int DepartmentId { get; set; }
        }   
    }
    namespace CodeFirstWithExistingDatabase.Models
    {
    
        [Table("Employee")] //<--Now, I have added this line of code
        public class Employee
        {
            public int Id { get; set; }
            public string Name { get; set; }
            [DataType(DataType.Currency)]
            [Column(TypeName = "decimal(18,4)")]
            public int DepartmentId { get; set; }
        }   
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 2011-07-14
      相关资源
      最近更新 更多