我正在使用 EF5 代码优先、迁移和每类型表继承。我有一些从其他类继承的类。例如,Tenant
和 Landlord
继承自 UserProfile
。
我正在使用 protected override void Seed()
方法将测试数据添加到我的数据库中。例如,我创建 2 个 UserProfile 对象、1 个租户和 1 个房东。如何确保租户实体与第一个用户配置文件实体关联,而房东实体与第二个用户配置文件实体关联?因为我使用的是按类型表继承,所以我是否需要显式声明派生类的 UserId 等于其基类的 UserId ?我四处搜寻但找不到任何有用的东西。我尝试这样做:
protected override void Seed(Context context)
{
var users = new List<UserProfile>
{
new UserProfile { UserId=1, UserName="Matt", Email="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e1f3e1f501d1113" rel="noreferrer noopener nofollow">[email protected]</a>", AccountType=AccountType.Tenant },
new UserProfile { UserId=2, UserName="Dave", Email="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e3c2e3ace1edef" rel="noreferrer noopener nofollow">[email protected]</a>", AccountType=AccountType.Landlord }
};
users.ForEach(u => context.UserProfile.AddOrUpdate(u));
context.SaveChanges();
var tenants = new List<Tenant>
{
new Tenant { UserId = users.Single(x => x.UserId = 1) /* other properties */ }
// ...
};
tenants.ForEach(t => context.Tenant.AddOrUpdate(t));
context.SaveChanges();
var landlords = new List<Landlord>
{
new Landlord { UserId = users.Single(x => x.UserId = 2) /* other properties */ }
// ...
};
landlords.ForEach(l => context.Tenant.AddOrUpdate(l));
context.SaveChanges();
}
最佳答案
您必须使用 DbContext 来加载要分配给它的实体。
这应该可以做到:
protected override void Seed(Context context)
{
var users = new List<UserProfile>
{
new UserProfile { UserId=1, UserName="Matt", Email="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117051703f727e7c" rel="noreferrer noopener nofollow">[email protected]</a>", AccountType=AccountType.Tenant },
new UserProfile { UserId=2, UserName="Dave", Email="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbba9bbaf5b8b4b6" rel="noreferrer noopener nofollow">[email protected]</a>", AccountType=AccountType.Landlord }
};
users.ForEach(u => context.UserProfile.AddOrUpdate(u));
context.SaveChanges();
var tenants = new List<Tenant>
{
new Tenant { UserId = users.Single(x => x.UserId = context.UserProfile.First(x=>x.UserId = 1)) /* other properties */ }
// ...
};
tenants.ForEach(t => context.Tenant.AddOrUpdate(t));
context.SaveChanges();
var landlords = new List<Landlord>
{
new Landlord { UserId = users.Single(x => x.UserId = context.UserProfile.First(x=>x.UserId = 2)) /* other properties */ }
// ...
};
landlords.ForEach(l => context.Tenant.AddOrUpdate(l));
context.SaveChanges();
}
关于c# - Entity Framework - 如何将测试数据播种到使用每类型表继承的实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14674069/