[英]Entity Framework Code First, 1:1 association with inheritance
我有一个抽象类UserProfile
,它有一个Tenant
子类,所以关系是1:1-一个'user'是一个'tenant'。
这是在1:1基础上实现每个类型的表继承的正确方法吗?
[Table("UserProfile")]
public abstract class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
// ...
}
[Table("Tenant")]
public class Tenant : UserProfile
{
public string PersonalDescription { get; set; }
// ...
// Navigation property on dependant end
public virtual UserProfile UserProfile { get; set; }
}
我将导航属性放置在关系的从属端是否正确? 还是到底要紧吗?
我是否还需要在UserProfile
放置Tenant
类型的导航属性?
最后,我读到值得将模型中的每个属性virtual
以帮助EF进行更改跟踪-这是否必要?
在每种类型的方案中,您不需要导航属性。 租户不包含UserProfile,租户是UserProfile。
EF应该能够从Tenant表中获取Tenant字段的值,并从UserProfile表中获取从UserProfile继承的字段。 看起来很神奇,但它至少对我有用:)
至于DbSets,如果需要直接使用一个Tenant
集合,你可以添加一个Tenants
DbSet。 这将使您能够:
myContext.Tenants.Where(t => ... t.PersonalDescription ... t.UserId ...)
相当于更长和更少被发现
myContext.UserProfiles.OfType<Tenant>.Where(t => ....)
我个人的喜好是根本不使用声明的DbSet,而直接在包装存储库中使用Set<T>()
方法,该方法公开了诸如GetByKey
, Update
等之类的方法,但这只是一个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.