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