微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Entity Framework Core Code First无法与现有数据库一起使用

如何解决Entity Framework Core Code First无法与现有数据库一起使用

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

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

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

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();
        }
    }
}

现在,我已经在Package Manager控制台中执行了以下命令。

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",//        Salary = table.Column<decimal>(nullable: false),//        DepartmentId = table.Column<int>(nullable: false)
    //    },//    constraints: table =>
    //    {
    //        table.PrimaryKey("PK_Employees",x => x.Id);
    //    });
}

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

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 执行项目。但是,我没有从数据库表中获取行。也没有错误

解决方法

我找到了解决我问题的方法。解析非常简单,只需将[Table(name)]属性添加到Models文件夹中的那些类中,如下所示。

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; }
    }   
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。