[英]How can I insert the current date/time into a datetime data type field using Entity Framework?
I am using Entity Framework to insert a row of data into my Application table. 我正在使用实体框架在我的应用程序表中插入一行数据。
Here's the class: 这是课程:
public partial class Application
{
public Application()
{
this.TestAccounts = new List<TestAccount>();
}
public int ApplicationId { get; set; }
public string Name { get; set; }
public byte[] RowVersion { get; set; }
public System.DateTime ModifiedDate { get; set; }
public virtual ICollection<TestAccount> TestAccounts { get; set; }
}
Here's the C# code: 这是C#代码:
_Uow.Applications.Add(new Application { Name = name });
It's giving me an error saying 这给我一个错误的说法
InnerException: System.Data.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=System.Data.Entity
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=The conversion of a datetime2 data type to a datetime data type
resulted in an out-of-range value.
How can I change my C# code to insert the current date in the ModifiedDate field? 如何更改C#代码以在ModifiedDate字段中插入当前日期?
Simply that way: 就是这样:
_Uow.Applications.Add(new Application
{
Name = name,
ModifiedDate = DateTime.Now
});
Or you may do it in the constructor: 或者,您可以在构造函数中执行此操作:
public class Application
{
public Application()
{
ModifiedDate = DateTime.Now;
}
}
By the way: You got the exception because per default c# DateTime
is more precise than datetime
of SQL. 顺便说一句:您得到了例外,因为默认情况下,c# DateTime
比SQL的datetime
更精确。 Like the message says: Use datetime2
in SQL. 就像消息说的那样:在SQL中使用datetime2
。 DateTime
has it's min value as initial value, which is too low for SQL datetime
. DateTime
的最小值是初始值,对于SQL datetime
来说太低了。
You could specify a new constructor 您可以指定一个新的构造函数
public Application(string Name)
{
if(ModifiedDate == null)
//ModifiedDate = Convert.ToDateTime(01.01.2000);
ModifiedDate = DateTime.Now;
}
OR 要么
public Application(string Name, System.Nullable<DateTime> modifiedDate)
{
if(modifiedDate != null)
//ModifiedDate = Convert.ToDateTime(01.01.2000);
ModifiedDate = DateTime.Now;
else
Do stuff
}
This isn't beatifull, but should do the trick. 这不是很漂亮,但是应该可以解决。
hi your ModifiedDate
is initialized with minvalue as a result it gives an exception. 嗨,您的ModifiedDate
用minvalue初始化,因此它给出了异常。 Better to use either 更好地使用
public System.DateTime? ModifiedDate { get; set; } to make it nullable or
initialize in the construction 在构造中初始化
public Application()
{
this.TestAccounts = new List<TestAccount>();
ModifiedDate = DateTime.Now;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.