CF实体类中的EF CodeFirst计算字段 [英] EF CodeFirst computed field in CF entity class
问题描述
我已经将计算字段( Active
和 CreditsLeft
)直接添加到我的CodeFirst实体类中。在CF实体类中添加计算字段逻辑是个好主意?
I have added computed fields(Active
and CreditsLeft
) directly into my CodeFirst entity class. Is it good idea to add computed field logic inside CF Entity class?
public class User : Entity
{
public User()
{
Id = Helper.GetRandomInt(9);
DateStamp = DateTime.UtcNow;
TimeZone = TimeZoneInfo.Utc.Id;
}
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Email { get; set; }
[Required]
[MaxLength(50)]
public string Password { get; set; }
[MaxLength(50)]
public string FirstName { get; set; }
[MaxLength(50)]
public string LastName { get; set; }
[Required]
public DateTime DateStamp { get; set; }
public virtual ICollection<Order> Orders { get; set; }
public virtual ICollection<Statistic> Statistics { get; set; }
public virtual ICollection<Notification> Notifications { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public bool Active
{
get
{
return Orders.Any(c => c.Active && (c.TransactionType == TransactionType.Order || c.TransactionType == TransactionType.Subscription));
}
}
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int CreditsLeft
{
get
{
return Orders.Sum(p => p.Credits != null ? p.Credits.Value : 0);
}
}
}
推荐答案
在CF实体类中添加计算字段逻辑是个好主意?
Is it good idea to add computed field logic inside CF Entity class?
当然,你可以这样做,但有一些事情你必须要照顾。
Sure, you can do this, but there are a few things you must take care of.
首先,由业务逻辑计算的属性的属性是不是 [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
,因为这表示该值是在数据库中计算的(如计算列中)。您应该通过 [NotMapped]
属性来标记该属性。这告诉实体框架忽略数据库映射中的属性。
First, the attribute for a property that is computed by business logic is not [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
, because this indicates that the value is computed in the database (as in a computed column). You should mark the property by the [NotMapped]
attribute. This tells Entity Framework to ignore the property in database mapping.
其次,由于两个属性都使用 Orders
确保订单已加载,或者在访问任一属性时都可以加载。所以你可能要加载一个包含
语句( Include(user => ; user.Orders)
)。否则,您必须确保在 Active
或 CreditsLeft
被访问时,上下文仍然存在。
Second, since both properties use Orders
, you must make sure that the orders are loaded or can be lazy loaded when either property is accessed. So you may want to load User
s with an Include
statement (Include(user => user.Orders)
). Or else you must ensure that the context is still alive when Active
or CreditsLeft
is accessed.
第三,您不能直接在EF LINQ查询中查找属性,如
Third, you can't address the properties directly in an EF LINQ query, as in
db.Users.Select(u => u.Active);
因为EF会抛出一个异常,它不知道 Active
。您只能在内存中的物化用户对象上寻址属性。
because EF will throw an exception that it doesn't know Active
. You can address the properties only on materialized user objects in memory.
这篇关于CF实体类中的EF CodeFirst计算字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!