我需要在数据库中创建一些虚拟记录,但是当我使用下面的代码填充数据库时,它不会创建任何内容。
我没有错误,我可以看到种子方法正在运行。
我怀疑它与身份和自动增量等有关,但我不太确定。
我在表之间有一些递归表和关系,所以如何在Seed方法中处理这个?
namespace CalMeser.Data.Sql.Migrations
{
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.Diagnostics.Contracts;
using CalMeser.Data.Entities;
[ContractVerification(false)]
internal sealed class Configuration : DbMigrationsConfiguration<DataContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(DataContext context)
{
context.Tags.AddOrUpdate(new Tag
{
Name = "Computers",
Sort = 1,
Children = new List<Tag>
{
new Tag
{
Name = "Computer Science",
Sort = 1,
Children = new List<Tag>
{
new Tag
{
Name = "Programming",
Sort = 4
},
new Tag
{
Name = "Security",
Sort = 2
},
new Tag
{
Name = "Algorithms",
Sort = 3
},
new Tag
{
Name = "Data Structures",
Sort = 1
},
}
},
new Tag
{
Name = "Computer Information Systems",
Sort = 2
},
new Tag
{
Name = "Computer Engineering",
Sort = 3
}
}
});
context.Tags.AddOrUpdate(new Tag
{
Name = "Nature",
Sort = 1,
Children = new List<Tag>
{
new Tag
{
Name = "Animals",
Sort = 3,
Children = new List<Tag>
{
new Tag
{
Name = "Cats",
Sort = 1
},
new Tag
{
Name = "Dogs",
Sort = 2
},
new Tag
{
Name = "Fish",
Sort = 3
},
new Tag
{
Name = "Monkeys",
Sort = 4
},
}
},
new Tag
{
Name = "Plants",
Sort = 2,
Children = new List<Tag>
{
new Tag
{
Name = "Mint",
Sort = 1
},
new Tag
{
Name = "Sage",
Sort = 2
},
new Tag
{
Name = "Lime",
Sort = 3
}
}
},
new Tag
{
Name = "Space",
Sort = 1
}
}
});
context.SaveChanges();
}
}
}
以下是上述代码中使用的实体。
namespace CalMeser.Data.Abstractions
{
public abstract class Entity : IEntity
{
public long Id { get; set; }
}
}
namespace CalMeser.Data.Abstractions
{
using System.Collections.Generic;
public abstract class RecursiveEntity<TEntity> : Entity where TEntity : RecursiveEntity<TEntity>
{
public virtual IList<TEntity> Children { get; set; }
public virtual TEntity Parent { get; set; }
public long? ParentId { get; set; }
}
}
namespace CalMeser.Data.Entities
{
using CalMeser.Data.Abstractions;
public class Tag : RecursiveEntity<Tag>
{
public File Image { get; set; }
public string Name { get; set; }
public long Sort { get; set; }
}
}
答案 0 :(得分:0)
好吧,我决定放弃自动增量并继续使用Sequential Guid(COMB),这样我就可以预先计算该值并自己初始化它。
以下是一些帮助我做出此决定的文章和帖子。
GUIDs as fast primary keys under multiple databases
What are the performance improvement of Sequential Guid over standard Guid?
ID - Sequential Guid (COMB) Vs. Int Identity, using Entity Framework