【问题标题】:Error while insert items to context EF将项目插入上下文 EF 时出错
【发布时间】:2014-12-20 14:03:33
【问题描述】:

在我的种子方法中插入项目时出现错误

public class ContexInitializerDropAlways : DropCreateDatabaseAlways<DomainDbContext>
    {
        protected override void Seed(DomainDbContext context)
        {
            base.Seed(context);

            List<Tour> tours = new List<Tour>
            {
                new Tour
                {
                    Price = 800.00m,
                    StartedOn = DateTime.Now,
                    EndedOn = DateTime.Now.AddMonths(1),
                    Nights = 15
                },
                new Tour
                {
                    Price = 650.00m,
                    StartedOn = DateTime.Now.AddDays(10),
                    EndedOn = DateTime.Now.AddMonths(2),
                    Nights = 10
                },
                new Tour
                {
                    Price = 350m,
                    StartedOn = DateTime.Now.AddDays(5),
                    EndedOn = DateTime.Now.AddDays(5),
                    Nights = 5
                }
            };

            List<Country> countries = new List<Country>
            {
                new Country
                {
                    Name = "Австрия"
                },
                new Country
                {
                    Name = "Греция"
                },
                new Country
                {
                    Name = "Турция"
                }
            };

            countries[0].Tours.Add(tours[0]);
            countries[1].Tours.Add(tours[1]);
            countries[2].Tours.Add(tours[2]);

            context.Countries.AddRange(countries);
            context.SaveChanges();            
        }
    }

错误:违反主键约束“PK_dbo.Countries”。不能 在对象“dbo.Countries”中插入重复键。重复键 值为(00000000-0000-0000-0000-000000000000)。该声明有 被终止了。

【问题讨论】:

  • 表中有主键吗?
  • 是的,我愿意。 goo.gl/njrpWugoo.gl/yWeWFX
  • 你试过了吗?新国家{名称=“...”; ID = Guid.NewGuid(); }

标签: c# asp.net asp.net-mvc


【解决方案1】:

在您的Country 类中,请添加 key 属性。

public class Country
{ 
    [Key] 
    public Guid Id { get; set; } 

然后在你的代码中:

List<Country> countries = new List<Country>
        {
            new Country
            {
                Id = Guid.NewGuid();
                Name = "Австрия"
            },
             // etc.
        };

example.

【讨论】:

    【解决方案2】:

    有解决办法:

    public class CountryConfiguration : EntityTypeConfiguration<Country>
    {
        public CountryConfiguration()
        {
            Property(c => c.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 2017-07-01
      • 2021-05-11
      • 2020-08-22
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多