我有一个5列的数据表,其中一行被数据填充,然后通过事务保存到数据库。

保存时,返回一个错误:

将datetime2数据类型转换为datetime数据类型会导致值超出范围

它暗示,正如阅读,我的数据表有一个类型的DateTime2和我的数据库一个DateTime;这是错误的。

date列设置为DateTime,如下所示:

新数据专栏(“myDate, Type.GetType”)

问题

是否可以在代码中解决这个问题,或者是否必须在数据库级别上更改某些内容?


当前回答

在我的例子中,当为Nullable DateTime列显式分配NULL值时,然后尝试保存更改。这个错误将会弹出。

其他回答

在模型类的属性上添加下面提到的属性。

Attribute = [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
Reference = System.ComponentModel.DataAnnotations.Schema

最初我忘记添加这个属性。在我的数据库中,约束是这样创建的

ALTER TABLE [dbo].[TableName] ADD DEFAULT (getdate()) FOR [ColumnName]

我添加了这个属性并更新了我的db,然后它就变成了

ALTER TABLE [dbo].[TableName] ADD CONSTRAINT [DF_dbo.TableName_ColumnName] DEFAULT (getdate()) FOR [ColumnName]

我发现这篇文章试图弄清楚为什么我总是得到以下错误,这是由其他答案解释的。

将datetime2数据类型转换为datetime数据类型会导致值超出范围。

使用可空的DateTime对象。 公共DateTime ?PurchaseDate{获取;设置;}

如果你使用实体框架 将edmx文件中的nullable属性设置为True

在我的SQL Server 2008数据库中,我有一个标记为不可空的DateTime列,但有一个GetDate()函数作为其默认值。当使用EF4插入新对象时,我得到了这个错误,因为我没有显式地在对象上传递DateTime属性。我期望SQL函数为我处理日期,但它没有。我的解决方案是从代码中发送日期值,而不是依赖数据库来生成它。

obj.DateProperty = DateTime.now; // C#

继承的datetime属性有问题

当不可为空的日期字段在插入/更新时值为null时,通常会显示此错误消息。其中一个原因可能是遗传。

如果你的日期是从基类继承的,你不做映射EF将不会读取它的值。

欲了解更多信息: https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines

创建一个基于@sky-dev实现的基类。所以这可以很容易地应用到多个上下文和实体中。

public abstract class BaseDbContext<TEntity> : DbContext where TEntity : class
{
    public BaseDbContext(string connectionString)
        : base(connectionString)
    {
    }
    public override int SaveChanges()
    {

        UpdateDates();
        return base.SaveChanges();
    }

    private void UpdateDates()
    {
        foreach (var change in ChangeTracker.Entries<TEntity>())
        {
            var values = change.CurrentValues;
            foreach (var name in values.PropertyNames)
            {
                var value = values[name];
                if (value is DateTime)
                {
                    var date = (DateTime)value;
                    if (date < SqlDateTime.MinValue.Value)
                    {
                        values[name] = SqlDateTime.MinValue.Value;
                    }
                    else if (date > SqlDateTime.MaxValue.Value)
                    {
                        values[name] = SqlDateTime.MaxValue.Value;
                    }
                }
            }
        }
    }
}

用法:

public class MyContext: BaseDbContext<MyEntities>
{

    /// <summary>
    /// Initializes a new instance of the <see cref="MyContext"/> class.
    /// </summary>
    public MyContext()
        : base("name=MyConnectionString")
    {
    }
    /// <summary>
    /// Initializes a new instance of the <see cref="MyContext"/> class.
    /// </summary>
    /// <param name="connectionString">The connection string.</param>
    public MyContext(string connectionString)
        : base(connectionString)
    {
    }

     //DBcontext class body here (methods, overrides, etc.)
 }