将值插入Core 2.2中的Identity列

时间:2019-02-25 06:36:30

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

尝试在MSSQL Server中播种数据库。 “ 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的消息...

1 个答案:

答案 0 :(得分:0)

我认为错误在这里

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

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

Im使用.net core 2.1和EFcore 2.2.2。

我希望有帮助。