![](/img/trans.png)
[英]Why there are two “.tt” files generated when I use database first approach in Entity Framework?
[英]Making use of a generated entity's class constructor when using Entity Framework Database First
我正在使用數據庫優先,對模式的每次更新我都會更新EDMX文件,它會為我的模型生成新的類。 不幸的是,它不會生成我在數據庫中指定的默認列值(諸如“ TimeStamp”之類的默認值為“ getdate()”的列)。
這是生成的Student.cs
類的外觀:
namespace ABC.Data
{
using System;
public partial class Student
{
public Student()
{
}
public int StudentID { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> TimeStamp { get; set; }
}
}
有沒有一種方法可以使構造函數始終將TimeStamp
設置為當前日期? 我試過在具有相同名稱等的相同名稱空間中創建一個helper局部類,但是它不起作用。 也許我在助手類上做錯了。 理想情況下,即使生成新的模型類,我也希望助手類保持不變。
DbContext
類具有一個稱為ObjectMaterialized
的事件,您可以將其連接到...
context.ObjectMaterialized += ObjectContext_OnObjectMaterialized
此事件處理程序可以應用默認值。
private void ObjectContext_OnObjectMaterialized(
object sender, ObjectMaterializedEventArgs e)
{
if (e.Entity is Student)
(e.Entity as Student).TimeStamp = <default value>;
}
當需要新的Student
實例而不是更新實例時,您需要記住使用context.Set<Student>().Create()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.