NodaTime如何与EF Code First一起使用? [英] How can NodaTime be used with EF Code First?
问题描述
我真的希望能够在我的实体框架代码第一个数据库项目中使用NodaTime,但没有找到一个干净的方法。我真正想做的是这样的:
I really want to be able to use NodaTime in my Entity Framework Code First database projects but haven't found a "clean" way to do it. What I really want to do is this:
public class Photoshoot
{
public Guid PhotoshootId{get; set;}
public LocalDate ShootDate{get; set;} //ef ignores this property
}
是否有任何支持或推荐的方法使用NodaTime与EF代码优先?
Is there any supported or recommended approach to using NodaTime with EF Code First?
推荐答案
在Entity Framework中本来支持自定义原始类型持久性,常见的工作是使用好友属性。
Until custom primitive type persistence is natively supported in Entity Framework, a common work around is to use buddy properties.
对于域模型中的每个自定义基元,您将创建一个关联的映射原语,以Entity Framework支持的格式保存该值。然后根据其对应的好友属性的值计算自定义原始属性。
For each custom primitive within your domain model, you create an associated mapped primitive to hold the value in a format supported by Entity Framework. The custom primitive properties are then calculated from the value of their corresponding buddy property.
例如:
public class Photoshoot
{
// mapped
public Guid PhotoshootId{get; set;}
// mapped buddy property to ShootDate
public DateTime ShootDateValue { get; set; }
// non-mapped domain properties
public LocalDate ShootDate
{
get { // calculate from buddy property }
set { // set the buddy property }
}
}
我们在代码中使用NodaTime POCO正好使用这种方法。
We use NodaTime in our code first POCO's using exactly this approach.
很明显,这将使您具有一个类似于代码第一个POCO和一个域类型的类型。这可以通过将不同的职责分为两种类型和映射来改善复杂性。一个半途径的替代方法是将域属性推入一个子类型,并使所有映射好友的属性受到保护。使用一定数量的wanging实体框架可以映射到受保护的属性。
Obviously this leaves you with a single type acting as both a code first POCO and a domain type. This can be improved at the expense of complexity by separating out the different responsibilities into two types and mapping between them. A half-way alternative is to push the domain properties into a subtype and make all mapped buddy properties protected. With a certain amount of wanging Entity Framework can be made to map to protected properties.
这个相当辉煌的博客文章评估了实体框架对各种域建模构造的支持,包括封装的原语。这是我最初在设置我们的POCO时发现好友属性的概念的地方:
http://lostechies.com/jimmybogard/2014/04/29/domain-modeling-with-entity-framework-scorecard/
This rather splendid blog post evaluates Entity Framework support for various domain modelling constructs including encapsulated primitives. This is where I initially found the concept of buddy properties when setting up our POCO's: http://lostechies.com/jimmybogard/2014/04/29/domain-modeling-with-entity-framework-scorecard/
该系列中的另一篇博客文章讨论了映射到受保护的属性: http://lostechies.com/jimmybogard/2014/05/09/missing-ef-feature-workarounds-encapsulated-collections/
A further blog post in that series discusses mapping to protected properties: http://lostechies.com/jimmybogard/2014/05/09/missing-ef-feature-workarounds-encapsulated-collections/
这篇关于NodaTime如何与EF Code First一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!