是否有可能拥有实体框架(我目前使用的是Code First Approach with CTP5)将所有DateTime值存储为数据库中的UTC?
或者是否有一种方法可以在映射中指定它,例如在last_login列的这一个中:
modelBuilder.Entity<User>().Property(x => x.Id).HasColumnName("id");
modelBuilder.Entity<User>().Property(x => x.IsAdmin).HasColumnName("admin");
modelBuilder.Entity<User>().Property(x => x.IsEnabled).HasColumnName("enabled");
modelBuilder.Entity<User>().Property(x => x.PasswordHash).HasColumnName("password_hash");
modelBuilder.Entity<User>().Property(x => x.LastLogin).HasColumnName("last_login");
Run Code Online (Sandbox Code Playgroud) 我首先使用EF 4数据库+ POCO.因为EF没有简单的方法来声明传入的DateTimes是种类的UTC,所以我将属性从自动生成的文件移动到另一个文件中的部分类.
private DateTime _createdOn;
public virtual System.DateTime CreatedOn
{
get { return _createdOn; }
set
{
_createdOn =
(value.Kind == DateTimeKind.Unspecified)
? _createdOn = DateTime.SpecifyKind(value, DateTimeKind.Utc)
: value;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,现在每次更新模型时,都会在T4代中再次创建自动化属性.当然这会导致以下编译错误:"类型'Foo'已包含'CreatedOn'的定义".
有没有办法告诉EF不生成该属性并让我自己处理它?
更新
谢谢大家的答案......
我创建了一个具有不同名称的新自定义属性.
public virtual System.DateTime CreatedOnUtc
{
get
{
return (CreatedOn.Kind==DateTimeKind.Unspecified)
? DateTime.SpecifyKind(CreatedOn, DateTimeKind.Utc)
: CreatedOn;
}
set
{
CreatedOn =
(value.Kind == DateTimeKind.Unspecified)
? CreatedOn = DateTime.SpecifyKind(value, DateTimeKind.Utc)
: value;
}
}
Run Code Online (Sandbox Code Playgroud)
我还将自动生成属性的所有setter和getter设置为Private,但我需要在Linq-to-Entities查询(叹气)中使用这些属性.在这些情况下,我将这些吸气剂设置为内部.
我确定希望在DateTime类型上有一个下拉列表,指定EF应该将其视为DateTime的"种类".这样可以节省数小时和额外的复杂功能.
是否可以在Kind == DateTimeKind.Utc 使用.edmx文件或t4模板的实体对象中定义DateTime属性?
如果可能,使用t4,请描述如何更改属性.目前该属性生成为:
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.DateTime Created
{
get
{
return _created;
}
internal set
{
OnCreatedChanging(value);
ReportPropertyChanging("Created");
_created = StructuralObject.SetValidValue(value);
ReportPropertyChanged("Created");
OnCreatedChanged();
}
}
private global::System.DateTime _created;
partial void OnCreatedChanging(global::System.DateTime value);
partial void OnCreatedChanged();
Run Code Online (Sandbox Code Playgroud)