.NET Core 2.2 - Entity Framework - 自定义分配 [NotMapped] 模型属性 w/ DbSet.FromSql()
.NET Core 2.2 - Entity Framework - Custom Assign [NotMapped] Model Attribute w/ DbSet.FromSql()
我有一个 .NET Core 2.2 API 项目。我正在尝试设置具有自定义属性的 EF 模型 class,这些属性未直接映射到 table 中的字段, 通常 会 NULL
,但在一个实例中将被自定义分配。
这是(概念上的)我的模型:
public class SomeObject {
[Key]
public int ID { get; set; }
[NotMapped]
public string CustomField1 { get; set; }
[NotMapped]
public string CustomField2 { get; set; }
}
在代码的其他地方,我基本上是这样的:
return SomeObjects
.FromSql($@"select *, <custom mapping here> as CustomField1, <custom mapping here> as CustomField2 from [table name]")
我希望映射器能够根据字段名称匹配在幕后解决问题,但这行不通。
或者,我希望在 Rails 或 Laravel 上使用 Ruby 中的 map()
方法,在那里我可以做这样的事情:
return SomeObjects
.FromSql($@"select *, <custom mapping here> as CustomField1, <custom mapping here> as CustomField2 from [table name]")
.Map( o => { o.CustomField1 = CustomField1, o.CustomField2 = CustomField2 });
如果它存在我也不会感到惊讶,我只是想念它。我还没有找到任何关于它的文档,但也许我只是没有用谷歌搜索正确的东西。
想法?
尝试使用从实体类型 SomeObjects
继承的附加 CustomFieldX
属性定义子类型,以利用通用属性和映射。我讨厌硬编码 SQL(破坏了 ORM 的主要目的之一)并且更喜欢视图或存储过程,然后您可以将子类型映射到该视图或存储过程。
我有一个 .NET Core 2.2 API 项目。我正在尝试设置具有自定义属性的 EF 模型 class,这些属性未直接映射到 table 中的字段, 通常 会 NULL
,但在一个实例中将被自定义分配。
这是(概念上的)我的模型:
public class SomeObject {
[Key]
public int ID { get; set; }
[NotMapped]
public string CustomField1 { get; set; }
[NotMapped]
public string CustomField2 { get; set; }
}
在代码的其他地方,我基本上是这样的:
return SomeObjects
.FromSql($@"select *, <custom mapping here> as CustomField1, <custom mapping here> as CustomField2 from [table name]")
我希望映射器能够根据字段名称匹配在幕后解决问题,但这行不通。
或者,我希望在 Rails 或 Laravel 上使用 Ruby 中的 map()
方法,在那里我可以做这样的事情:
return SomeObjects
.FromSql($@"select *, <custom mapping here> as CustomField1, <custom mapping here> as CustomField2 from [table name]")
.Map( o => { o.CustomField1 = CustomField1, o.CustomField2 = CustomField2 });
如果它存在我也不会感到惊讶,我只是想念它。我还没有找到任何关于它的文档,但也许我只是没有用谷歌搜索正确的东西。
想法?
尝试使用从实体类型 SomeObjects
继承的附加 CustomFieldX
属性定义子类型,以利用通用属性和映射。我讨厌硬编码 SQL(破坏了 ORM 的主要目的之一)并且更喜欢视图或存储过程,然后您可以将子类型映射到该视图或存储过程。