【发布时间】:2017-04-17 20:17:14
【问题描述】:
我正在尝试在实体框架中实现分层继承结构,专门用于设置。例如,假设我们有用户偏好:
public class StorePreference: Preference { }
public class UserPreference : Preference { }
public class Preference {
public string BackgroundColor { get; set; }
public ContactMethod ContactMethod { get; set; }
}
public enum ContactMethod {
SMS,
Email
}
如果我查找用户的偏好,我会喜欢它。如果用户不存在或属性值为 null,则查找父(存储)默认首选项。
理想情况下,我希望它类似于抽象继承:
public class UserPreference : StorePreference {
private string _backgroundColor;
public string BackgroundColor {
get {
if (this._backgroundColor == null)
return base;
return this._backgroundColor;
}
set { this._backgroundColor = value; }
}
}
如果我将其编写为 SQL 查询,它将是一个带有 CASE 语句的 CROSS APPLY:
SELECT
CASE WHEN User.BackgroundColor == null THEN Store.BackgroundColor ELSE User.BackgroundColor END BackgroundColor,
CASE WHEN User.ContactMethod == null THEN Store.ContactMethod ELSE User.ContactMethod END ContactMethod
FROM UserPreference User
CROSS APPLY StorePreference Store
WHERE UserPreference.UserId = @UserId
有没有办法可以在 EF 中加载它?
【问题讨论】:
标签: c# entity-framework cross-apply