使用 c#和 EF , linq 。我有这个基本模型:
public class BaseModel {
[Key]
public int Id { get; set; }
}
这些课程:
public class ModelA: BaseModel {
public virtual string PropertyA { get; set; }
}
public class ModelB: BaseModel {
public virtual string PropertyB { get; set; }
}
public class Model: BaseModel {
public virtual BaseModel Entity { get; set; }
public virtual string EntityType { get; set; }
}
DbContext
上的这些配置:
public IDbSet<ModelA> ModelsA { get; set; }
public IDbSet<ModelB> ModelsB { get; set; }
public IDbSet<Model> Models { get; set; }
以这种方式创建和保存实例:
var modelA = new ModelA { Id=1, PropertyA = "ValueA" };
dbContext.ModelsA.Add(modelA);
var modelB = new ModelB { Id=2, PropertyB = "ValueB" };
dbContext.ModelsB.Add(modelB);
var model1 = new Model { Entity = modelA, EntityType = nameof(ModelA) };
dbContext.Models.Add(model1);
var model2 = new Model { Entity = modelB, EntityType = nameof(ModelB) };
dbContext.Models.Add(model2);
是否有办法直接从ModelA
恢复ModelB
/ Models
的实例?我的意思是,有一种:
var modelsAList = dbContext.Models
.Where(m=>m.EntityType=='ModelA')
.Select(m=>m.Entity as ModelA)
.ToList();
(上面的代码不起作用,只是为了说明我的需要)