【问题标题】:Insert value into identity column in Core 2.2在 Core 2.2 中将值插入标识列
【发布时间】:2019-07-18 12:46:18
【问题描述】:

尝试在 MSSQL 服务器中播种数据库。 'Id' 列设置为标识。我不明白为什么 EF 需要 'Id: 的数据:

public class Location
{
    public int? Id { get; set; }

    public string Name { get; set; }

    public IList<Office> Offices { get; set; }

}

...流畅的API:

modelBuilder.Entity<Location>()
     .HasKey(k => k.Id);

modelBuilder.Entity<Location>()
     .Property(p => p.Id)
     .UseSqlServerIdentityColumn()
     .ValueGeneratedOnAdd();

modelBuilder.Entity<Location>()
     .HasData(
            new Location() { Name = "Sydney" },
            new Location() { Name = "Melbourne" },
            new Location() { Name = "Brisbane" }
    );

...据我了解,如果“Id”是由服务器在插入时生成的,则不需要提供。为什么我会收到关于不提供 ID 的消息...

【问题讨论】:

    标签: entity-framework-core ef-fluent-api seeding identity-column


    【解决方案1】:

    我认为错误就在这里

    public int? Id { get; set; }
    

    Id 不应为空。

    更新: 我的意思是你应该写:

    public int Id { get; set; }
    

    问号使您的属性可以为空,但由于它是主键,因此不能为空。

    我在这里做了一个小例子:

    using System.Collections.Generic;
    
    namespace ConsoleApp2.Models
    {
        public class Location
        {
            public int Id { get; set; }
    
            public string Name { get; set; }
    
            public IList<Office> Offices { get; set; }
        }
    }
    

    流利的API

          migrationBuilder.CreateTable(
                    name: "Locations",
                    columns: table => new
                    {
                        Id = table.Column<int>(nullable: false)
                            .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                        Name = table.Column<string>(nullable: true)
                    },
                    constraints: table =>
                    {
                        table.PrimaryKey("PK_Locations", x => x.Id);
                    });
    

    我可以毫无问题地添加新位置。

    using ConsoleApp2.Models;
    using System.Collections.Generic;
    
    namespace ConsoleApp2
    {
        class Program
        {
            static void Main(string[] args)
            {
                MyDbContext _c = new MyDbContext();
    
                List<Office> list = new List<Office>()
                {
                      new Office()
                    {
                        OfficeName = "Reception"
                    }
                };
    
    
                Location l = new Location()
                {
                    Name = "New York",
                    Offices = list
                };
    
                _c.Locations.Add(l);
                _c.SaveChanges();
            }
        }
    }
    
    

    我正在使用 .net core 2.1 和 EFcore 2.2.2。

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-31
      • 2019-05-28
      • 1970-01-01
      • 2019-06-25
      • 2012-06-23
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      相关资源
      最近更新 更多