【发布时间】:2018-01-26 17:50:06
【问题描述】:
我正在使用 ASP.NET Core 和带有 MySQL 的 EF Core 制作休息服务器。
数据库中有两个表 - 建筑物和建筑物参数。每种建筑类型都有不同的变量,所以我决定用这种方式解决这个问题。
所以有模型Building,但也有很多继承自Building 的建筑类。一个小例子:
[BuildingType(EBuildingType.Stable)]
public class Building_Stable : Building
{
public int Slots
{
get
{
return GetArgumentValueOrDefault<int>("Slots");
}
set
{
UpdateOrCreateArgument("Slots", value);
}
}
}
我可以访问所有 Building 属性,并且可以以非常愉快的方式获取和设置其他属性(数据库中的参数)。当我想从我的存储库中构建时,我正在这样做:
public async Task<TBuilding> GetByType<TBuilding>(User user) where TBuilding : Building
{
try
{
if (user == null) return null;
EBuildingType? type;
type = _buildingTypesCollection.GetType(typeof(TBuilding));
if (type == null) return null;
Building uBuilding = await _dbContext.Buildings.Where(b => b.Type == type && b.OwnerId == user.Id).Include(p => p.Arguments).FirstOrDefaultAsync();
var parent = JsonConvert.SerializeObject(uBuilding);
TBuilding c = JsonConvert.DeserializeObject<TBuilding>(parent);
return c;
}
catch (Exception ex)
{
throw ex;
}
}
它在大多数情况下都有效,但有时我不得不对如何访问某些属性感到非常困惑,而且我并不完全满足。所以我有这种感觉,我做的不对。
【问题讨论】:
-
我猜你正在使用 EF TPH 继承,
Type属性是鉴别器?
标签: c# entity-framework asp.net-core entity-framework-core