我是Entity Framework的新手,过去我直接使用Enterprise Library或ADO.NET将模型映射到数据库表.我使用的一种模式是将我的公共审计字段放在基类中的每个表中,然后为每个对象继承该基类.
我采取两个步骤来保护两个字段(Created,CreatedBy):
在Base Enitity上创建一个无参数构造函数私有,并创建第二个需要Created和CreatedBy的构造函数在创建时传递.
使setter Private,以便在创建对象后无法更改值.
基类:
using System; namespace App.Model { [Serializable()] public abstract class BaseEntity { public bool IsActive { get; private set; } public DateTimeOffset Created { get; private set; } public string CreatedBy { get; private set; } public DateTimeOffset LastUpdated { get; protected set; } public string LastUpdatedBy { get; protected set; } private BaseEntity() { } protected BaseEntity(DateTimeOffset created, string createdBy) { IsActive = true; Created = created; CreatedBy = createdBy; LastUpdated = created; LastUpdatedBy = createdBy; } } }
继承类:
using System; namespace App.Model { [Serializable()] public class Person : BaseEntity { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public Person(DateTimeOffset created, string createdBy) : base(created, createdBy) { } } }
我遇到了两个问题.EF需要无参数构造函数来创建对象.EF不会创建具有私有setter的数据库列.
我的问题是,如果有更好的方法来实现我的EF目标:
要求在实例化时填充Created和CreatedBy的值.
无法更改Created和CreatedBy的值.
Gert Arnold.. 5
您可以使用接受字符串的构造函数实例化上下文createdBy
.然后在覆盖SaveChanges()
:
public override int SaveChanges() { foreach( var entity in ChangeTracker.Entries() .Where(e => e.State == EntityState.Added) .Select (e => e.Entity) .OfType()) { entity.SetAuditValues(DateTimeOffset.Now, this.CreatedBy); } return base.SaveChanges(); }
与SetAuditValues()
作为
internal void SetAuditValues(DateTimeOffset created, string createdBy) { if (this.Created == DateTimeOffset.MinValue) this.Created = created; if (string.IsNullOrEmpty(this.CreatedBy)) this.CreatedBy = createdBy; }
从数据库实现实体后,当有人调用时,不会覆盖这些值SetAuditValues
.
您可以使用接受字符串的构造函数实例化上下文createdBy
.然后在覆盖SaveChanges()
:
public override int SaveChanges() { foreach( var entity in ChangeTracker.Entries() .Where(e => e.State == EntityState.Added) .Select (e => e.Entity) .OfType()) { entity.SetAuditValues(DateTimeOffset.Now, this.CreatedBy); } return base.SaveChanges(); }
与SetAuditValues()
作为
internal void SetAuditValues(DateTimeOffset created, string createdBy) { if (this.Created == DateTimeOffset.MinValue) this.Created = created; if (string.IsNullOrEmpty(this.CreatedBy)) this.CreatedBy = createdBy; }
从数据库实现实体后,当有人调用时,不会覆盖这些值SetAuditValues
.