通过实体框架模式创建时,SQL Server表中未设置默认值 [英] Default values doesn't set in SQL Server table when creating by Entity Framework mode

查看:60
本文介绍了通过实体框架模式创建时,SQL Server表中未设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多包含默认值的表,例如 CreatedDateTime(getutcdate()).但是,现在,将存储值0001-01-01 00:00:00.0000000.

I have lots of tables that contain default values, such as CreatedDateTime (getutcdate()). But right now, the value 0001-01-01 00:00:00.0000000 gets stored instead.

https://stackoverflow.com/a/35093135/7731479 ->无效,我有为每个数据库模型更新(edmx)手动为每个表执行操作.如何将所有StoreGeneratedPattern更新为自动计算?还是为什么它不自动进行计算?

https://stackoverflow.com/a/35093135/7731479 --> that is not effective, I have to do it for each table manually for every database model update (edmx). How can I update all StoreGeneratedPattern to Computed automatically? Or why it does not takes computed automatically?

https://stackoverflow.com/a/43400053/7731479 -> ado.net会生成所有属性,并我无法再次生成 CreatedDateTime .

https://stackoverflow.com/a/43400053/7731479 --> ado.net generates all properties and I can't generate again CreatedDateTime.

有没有自动解决方案?

我正在使用Entity Framework和ado.net.

I am using Entity Framework and ado.net.

Person person = new Person()
{
    Id = id,
    Name = name,
};
AddToPerson(person);
SaveChanges();

我想在上面使用.我不想使用以下内容并再次分配CreatedDeteTime,因为它是在MSSQL中使用默认值getutcdate()分配的.

I want to use above. I don't want use the following and assign CreatedDeteTime again because it is assigned in MSSQL with default value getutcdate().

Person person = new Person()
{
    Id = id,
    Name = name,
    CreatedDeteTime = DateTime.UtcNow;
};
AddToPerson(person);
SaveChanges();

推荐答案

我发现了两种解决方案:

I have found two solutions:

1-此解决方案可解决具有相同属性(例如 CreatedDateTime

1- This solution solve for all entities that has same property such as CreatedDateTime

public partial class MyEntities : ObjectContext
    {
        public override int SaveChanges(SaveOptions options)
        {
            this.DetectChanges();

            foreach (var insert in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added))
            {
                if (insert.Entity.GetType().GetProperty("CreatedDateTime") != null && insert.Entity.GetType().GetProperty("CreatedDateTime").GetType().Name == "DateTime" && (DateTime)(insert.Entity.GetType().GetProperty("CreatedDateTime").GetValue(insert.Entity)) == DateTime.Parse("0001-01-01 00:00:00.0000000"))
                    insert.Entity.GetType().GetProperty("CreatedDateTime").SetValue(insert.Entity, DateTime.UtcNow, null);                
            }
            return base.SaveChanges(options);
        }
    }

引用: https://stackoverflow.com/a/5965743/7731479

2-

public partial class Person
        {
            public Person()
            {
                this.CreatedDateTime = DateTime.UtcNow;
            }
        }

引用:创建实体框架模型时忽略数据库默认值

这篇关于通过实体框架模式创建时,SQL Server表中未设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆