0

Entity Framework を使用して、アプリケーション テーブルにデータ行を挿入しています。

クラスは次のとおりです。

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; }
}

C# コードは次のとおりです。

_Uow.Applications.Add(new Application { Name = name });

それは私に言ってエラーを与えています

  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.

ModifiedDate フィールドに現在の日付を挿入するように C# コードを変更するにはどうすればよいですか?

4

3 に答える 3

0

新しいコンストラクタを指定できます

public Application(string Name)
{
  if(ModifiedDate == null)
   //ModifiedDate = Convert.ToDateTime(01.01.2000);
     ModifiedDate = DateTime.Now;
}

また

public Application(string Name, System.Nullable<DateTime> modifiedDate)
{
   if(modifiedDate != null)
     //ModifiedDate = Convert.ToDateTime(01.01.2000);
     ModifiedDate = DateTime.Now;
   else
   Do stuff
}

これは美しいものではありませんが、うまくいくはずです。

于 2013-03-25T10:44:51.660 に答える
0

こんにちは、ModifiedDateminvalue で初期化されているため、例外が発生します。どちらかを使ったほうがいい

public System.DateTime? ModifiedDate { get; set; } to make it nullable or

構築で初期化する

public Application()
    {
        this.TestAccounts = new List<TestAccount>();
        ModifiedDate = DateTime.Now;

    }
于 2013-03-25T10:46:38.577 に答える
0

単にそのように:

_Uow.Applications.Add(new Application
                       {
                           Name = name,
                           ModifiedDate = DateTime.Now
                       });

または、コンストラクターで実行することもできます。

public class Application
{
    public Application()
    {
        ModifiedDate = DateTime.Now;
    }
}

ちなみに、デフォルトではc#はSQLDateTimeよりも正確であるため、例外が発生しました。datetimeメッセージが言うように:datetime2SQLで使用してください。DateTime最小値を初期値として持っていますが、これは SQL には低すぎますdatetime

于 2013-03-25T10:36:44.873 に答える