将项目插入上下文EF时出错

时间:2014-12-20 14:03:34

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

在种子方法

中插入项目时出错
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();            
        }
    }
  

错误:违反PRIMARY KEY约束'PK_dbo.Countries'。不能   在对象'dbo.Countries'中插入重复键。重复的密钥   值为(00000000-0000-0000-0000-000000000000)。声明有   已被终止。

2 个答案:

答案 0 :(得分:1)

Country课程中,请添加关键属性。

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

然后在你的代码中:

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

example.

答案 1 :(得分:0)

有解决方案:

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