使用EF Code First创建数据库时出现无效的对象名称错误

时间:2019-12-16 08:35:04

标签: entity-framework-core ef-code-first .net-core-3.1

您好,我正在使用EF Core Code First开发数据库。生成数据库时,我总是收到此错误消息:

  

Microsoft.EntityFrameworkCore.DbUpdateException:'发生了错误   在更新条目时。有关详细信息,请参见内部异常。'

     
      
  • InnerException {“无效的对象名称“父母”。”} System.Exception {Microsoft.Data.SqlClient.SqlException}
  •   

从我阅读的内容来看,似乎我无法创建数据库,因为表以某种方式是复数的。 我已经搜索了包括此SO thread在内的解决方案,并尝试了无济于事的解决方案。我没有尝试过的是RemovePluralization方法,因为 我的Conventions中没有ModelBuilder字段,找不到包含它的软件包。

上下文和模型

          public class Parent {
            public int ID { get; set; }
            public string Name { get; set; }
            public ICollection<Child> Children { get; set; }
            public Parent() {
                this.Children = new List<Child>();
            }
        }

        public class Child {
            public int ID { get; set; }
            public string Name { get; set; }
            public Parent Parent { get; set; }
            public int ParentId { get; set; }
        }
        public class MyContext : DbContext {
            public virtual DbSet<Parent> Parents { get; set; }
            public virtual DbSet<Child> Children { get; set; }
            protected override void OnModelCreating(ModelBuilder modelBuilder) {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<Child>()
                    .HasKey(x => x.ID);
                modelBuilder.Entity<Parent>()
                    .HasKey(x => x.ID);
                modelBuilder.Entity<Parent>()
                    .HasMany(x => x.Children)
                    .WithOne(k=>k.Parent)
                    .HasForeignKey(t => t.ParentId);

            }
            public MyContext(DbContextOptions options):base(options) {

            this.Database.EnsureCreated();
            this.Database.Migrate(); //i have tried this too 
            }
      }

用法

var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
optionsBuilder.UseSqlServer(connectionString);
MyContext context = new MyContext(optionsBuilder.Options);
Parent parent = new Parent() { Name = "Parentino" };
context.Parents.Add(parent);
await context.SaveChangesAsync(); //crashes with before mentioned error

我还尝试在OnModelCreating重载中设置表名:

modelBuilder.Entity<Parent>().ToTable("parent");

或直接在我的Model类上具有[Table("name")]属性,无济于事。

有人可以帮我一下,告诉我为什么我不能生成数据库吗?

1 个答案:

答案 0 :(得分:1)

对我来说很好

program.sc

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string connectionString = "Server=(localdb)\\MSSQLLocalDB;Initial Catalog=test;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
            var optionsBuilder = new DbContextOptionsBuilder<MyContext>();
            optionsBuilder.UseSqlServer(connectionString);
            MyContext context = new MyContext(optionsBuilder.Options);
            Parent parent = new Parent() { Name = "Parentino" };
            context.Parents.Add(parent);
            await context.SaveChangesAsync(); //crashes with before mentioned error        }
        }
    }

    public class Parent
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public ICollection<Child> Children { get; set; }
        public Parent()
        {
            this.Children = new List<Child>();
        }
    }

    public class Child
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public Parent Parent { get; set; }
        public int ParentId { get; set; }
    }
    public class MyContext : DbContext
    {
        public virtual DbSet<Parent> Parents { get; set; }
        public virtual DbSet<Child> Children { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Child>()
                .HasKey(x => x.ID);
            modelBuilder.Entity<Parent>()
                .HasKey(x => x.ID);
            modelBuilder.Entity<Parent>()
                .HasMany(x => x.Children)
                .WithOne(k => k.Parent)
                .HasForeignKey(t => t.ParentId);

        }
        public MyContext(DbContextOptions options) : base(options)
        {

            this.Database.EnsureCreated();
            this.Database.Migrate(); //i have tried this too 
        }
    }
}

ConsoleApp1.csproj


  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

</Project>