如何一步一步创建EF Core ID?

时间:2019-03-21 13:59:52

标签: entity-framework entity-framework-core

我正在学习EF Core,并在下面的POCO Road的物业出租处创建ID

public class Road
{
    public int rid { get; set; }
    public string rname { get; set; }
    public string zip { get; set; }
},

目前,我的解决方案分为两步:

1:添加PK

2:使用ValueGeneratedOnAdd()方法

modelBuilder.Entity<Road>()
       .HasKey(x => x.rid);

modelBuilder.Entity<Road>()
       .Property(x =>x.rid)
       .ValueGeneratedOnAdd();

我想要一个一步的解决方案,怎么做?

2 个答案:

答案 0 :(得分:0)

        public class Road
        {
            [Key]
            public int rid { get; set; }

            public string rname { get; set; }
            public string zip { get; set; }
        },

答案 1 :(得分:0)

您可以创建扩展方法:

public static class ModelBuilderExtensions 
{
    public static EntityTypeBuilder<T> HasKeyWithValueGeneratedOnAdd<T>(
        this EntityTypeBuilder<T> b,
        Expression<Func<T, object>> expression) 
    where T : class
    {
      b.HasKey(expression);
      b.Property(expression).ValueGeneratedOnAdd();
      return b;
    }
}

然后将其用作单线:

modelBuilder.Entity<Road>().HasKeyWithValueGeneratedOnAdd(x => x.rid);