LINQ to SQL不的方式,你可以随后更新值观察数据库的默认值。为了做到这一点,您需要在代码中设置默认值。
当创建一个是NOT NULL
与数据库默认新对象,C#将使用默认值,如MinValue
数字和日期的,空的GUID(零),等等。你可以考虑到这些情况,并与自己的默认替换值。
这是LINQ To SQL的已知设计问题。对于一个深入的讨论,请参阅以下链接:
http://www.codeproject.com/KB/linq/SettingDefaultValues.aspx
在应用程序中设置默认值的一些示例代码:
private void SetDefaults(object LinqObj)
{
// get the properties of the LINQ Object
PropertyInfo[] props = LinqObj.GetType().GetProperties();
// iterate through each property of the class
foreach (PropertyInfo prop in props)
{
// attempt to discover any metadata relating to underlying data columns
try
{
// get any column attributes created by the Linq designer
object[] customAttributes = prop.GetCustomAttributes
(typeof(System.Data.Linq.Mapping.ColumnAttribute), false);
// if the property has an attribute letting us know that
// the underlying column data cannot be null
if (((System.Data.Linq.Mapping.ColumnAttribute)
(customAttributes[0])).DbType.ToLower().IndexOf("not null") != -1)
{
// if the current property is null or Linq has set a date time
// to its default '01/01/0001 00:00:00'
if (prop.GetValue(LinqObj, null) == null || prop.GetValue(LinqObj,
null).ToString() == (new DateTime(1, 1, 1, 0, 0, 0)).ToString())
{
// set the default values here : could re-query the database,
// but would be expensive so just use defaults coded here
switch (prop.PropertyType.ToString())
{
// System.String/NVarchar
case "System.String":
prop.SetValue(LinqObj, String.Empty, null);
break;
case "System.Int32":
case "System.Int64":
case "System.Int16":
prop.SetValue(LinqObj, 0, null);
break;
case "System.DateTime":
prop.SetValue(LinqObj, DateTime.Now, null);
break;
}
}
}
}
catch
{
// could do something here ...
}
}
相似问题:http:// stackoverflow。问题/ 201706 /如何做,我保证,LINQ到SQL-doesnt覆盖或违反,非可空数据库默认-V – bdukes 2010-11-29 16:34:13