如何通过手动将Id更改为自动递增来更改此设置

时间:2016-10-28 12:29:02

标签: asp.net asp.net-mvc entity-framework

有很多关于此的小写,但我无法理解。

此代码有效,但我必须手动指定Id,Id是其他几个表的外键:

种子

new Party {Id = "01", startDate = DateTime.Now, endDate = DateTime.Now }

模型

 public class Party
    {
        public string Id { get; set; }
        [DisplayFormat(DataFormatString = "{0:d}")]
        public DateTime startDate { get; set; }
        [DisplayFormat(DataFormatString = "{0:d}")]
        public DateTime endDate { get; set; }
    }

我想要做的就是这样,但是当我运行Update-Database -Verbose时,它会抛出一个错误,说Id正在被另一个表引用。如何使Id自动生成,以便在创建派对时不必引用它?:

种子

new Party {startDate = DateTime.Now, endDate = DateTime.Now }

模型

 public class Party
    {
       [Key]
        public string Id { get; set; }
        [DisplayFormat(DataFormatString = "{0:d}")]
        public DateTime startDate { get; set; }
        [DisplayFormat(DataFormatString = "{0:d}")]
        public DateTime endDate { get; set; }
    }

1 个答案:

答案 0 :(得分:0)

您需要将其设为Identity

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

public class Party
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime startDate { get; set; }

    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime endDate { get; set; }
}

现在您可以添加seed

protected override void Seed(ConsoleApplication1.TesteContext context)
{
    context.Parties.AddOrUpdate(
        p => p.Id,
        new Party { startDate = DateTime.Now, endDate = DateTime.Now },
        new Party { startDate = DateTime.Now.AddDays(1), endDate = DateTime.Now.AddDays(2) },
        new Party { startDate = DateTime.Now.AddDays(2), endDate = DateTime.Now.AddDays(3) },
        new Party { startDate = DateTime.Now.AddDays(3), endDate = DateTime.Now.AddDays(4) }
    );
}

你可以测试一下:

class Program
{
    static void Main(string[] args)
    {
        var ctx = new TesteContext();

        var parties = ctx.Parties.ToList();

        foreach(var party in parties)
        {
            Console.WriteLine($"Id: {party.Id}, Start: {party.startDate.ToShortDateString()}, End: {party.endDate.ToShortDateString()}");
        }

        Console.ReadKey();
    }
}