How do I ensure Linq to Sql doesn't override or violate non-nullable DB default values?

前端 未结 4 1647
天命终不由人
天命终不由人 2020-12-09 18:35

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

  1. A bit with the default value 1, NOT NULL.
  2. A smalldatetime
4条回答
  •  执笔经年
    2020-12-09 18:46

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

    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.

    • You could write a code generator to create entity partial classes where you can extract the default value constriant.
    • Alternatively your business layer code could set the defaults in constructors from an xml file, and all you need to do is keep the xml file up-to-date.
    • Instead of doing the work in constructors, you could emulate sql and add default values by inspecting the ChangeSet before submitting changes to the database.

    The issue you are having is described at length in CodeProject - Setting Default Values for LINQ Bound Data

提交回复
热议问题