如何确保 Linq to Sql 不会覆盖或违反不可为空的数据库默认值? [英] How do I ensure Linq to Sql doesn't override or violate non-nullable DB default values?

查看:17
本文介绍了如何确保 Linq to Sql 不会覆盖或违反不可为空的数据库默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有这些字段的表的 SQL Server 数据库:

I have an SQL Server DB with a table with these fields:

  1. 一个bit,默认值为1,NOT NULL.
  2. 一个smalldatetime,默认值为gettime()NOT NULL.
  3. 一个没有默认值的intIDENTITYNOT NULL.
  1. A bit with the default value 1, NOT NULL.
  2. A smalldatetime with the default value gettime(), NOT NULL.
  3. An int with no default value, IDENTITY, NOT NULL.

当我为此表生成 Linq to SQL 时,会发生以下情况:

When I generate Linq to SQL for this table, the following happens:

  1. bit 没有特殊处理.
  2. smalldatetime 没有特殊处理.
  3. int 被标记为 IsDbGenerated.
  1. The bit is given no special treatment.
  2. The smalldatetime is given no special treatment.
  3. The int is marked as IsDbGenerated.

这意味着当我使用 Linq to SQL 进行插入时,会发生以下情况:

This means that when I make inserts using Linq to SQL, the following will happen:

  1. bit 将作为 0 发送,覆盖默认值.对吗?
  2. smalldatetime 将作为未初始化的 System.DateTime 发送,在 SQL Server 中产生错误,因为它不属于 SQL Server smalldatetime 范围.对吗?
  3. IsDbGenerated int 不会被发送;DB 将生成一个值,然后 Linq to SQL 将读回该值.
  1. The bit will be sent as 0, overriding the default value. Right?
  2. The smalldatetime will be sent as an uninitialized System.DateTime, producing an error in SQL server since it doesn't fall with the SQL Server smalldatetime range. Right?
  3. The IsDbGenerated int will not be sent; the DB will generate a value which Linq to SQL will then read back.

我需要做哪些改变才能让这个场景发挥作用?

总结:我想要具有数据库分配的默认值的不可为空的字段,但我不想要它们 IsDbGenerated 如果这意味着我在使用 Linq 进行更新或插入时无法为它们提供值到 SQL.我也不想要它们 IsDbGenerated 如果这意味着我必须手动修改由 Linq to SQL 生成的代码.

To summarize: I want non-nullable fields with DB-assigned default values, but I don't want them IsDbGenerated if it means I cannot provide values for them when making updates or inserts using Linq to SQL. I also do not want them IsDbGenerated if it means I have to hand-modify the code generated by Linq to SQL.

答案似乎是当前 Linq to SQL 中的一个限制.

推荐答案

Linq-To-Sql 生成的类不选择默认值约束.

Linq-To-Sql generated classes do not pick up the Default Value Constriants.

也许在未来,但问题是约束并不总是简单的值,它们也可以是像 GetDate() 这样的标量函数,所以 linq 必须知道如何翻译它们.简而言之,它甚至不尝试.这也是一种非常特定于数据库的东西.

Maybe in the future, but the issue is constraints aren't always simple values, they can also be scalar functions like GetDate(), so linq would somehow have to know how to translate those. In short, it doesn't even try. It's also a very database-specific type of thing.

  • 您可以编写代码生成器来创建实体部分类,您可以在其中提取默认值约束.
  • 或者,您的业务层代码可以通过 xml 文件在构造函数中设置默认值,您需要做的就是保持 xml 文件是最新的.
  • 您可以在向数据库提交更改之前通过检查 ChangeSet 来模拟 sql 并添加默认值,而不是在构造函数中进行工作.

CodeProject - Setting Default Values for LINQ 中详细描述了您遇到的问题绑定数据

这篇关于如何确保 Linq to Sql 不会覆盖或违反不可为空的数据库默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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