日期:2014-05-20  浏览次数:20807 次

LINQ to SQL的问题,执行DataContext.SubmitChanges() 数据库并不更新,该如何解决?代码如内:
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;

namespace linqTest
{
class Program
{
static void Main(string[] args)
{
DataContext dc = new DataContext(@"Data Source=xxx;Initial Catalog=xxx;Integrated Security=True");
dc.Log = Console.Out;
Table<Customer> customerArray = dc.GetTable<Customer>();

// 执行到这里确实有T-SQL select 语句输出
Customer cc = customerArray.Single(s => s.NameAbbreviation == "Toronto");

cc.Name = "Beijing: "+DateTime.Now.ToLocalTime();

// 按理说执行到这里应该有相应的Update语句输出,可是就是什么都没有
dc.SubmitChanges();


Console.ReadLine();
}
}

[Table(Name = "dbo.Customer")]
class Customer
{

[Column]
public int CustomerID;

[Column]
public string Name;

[Column]
public string NameAbbreviation;

public override string ToString()
{
return CustomerID.ToString() + "," + Name + "," + NameAbbreviation;
}
}
}

编译运行没有任何问题,因为有
dc.Log = Console.Out;
所以所有生成的T-SQL语句都会动态的显示在Console上,当执行
Customer cc = customerArray.Single(s => s.NameAbbreviation == "Toronto");
的时候,LINQ显示出它所生成的T-SQL select 语句
但是当执行
dc.SubmitChanges();
的时候,没有任何T-SQL输出,然后就结束了,当然数据库也没有任何更新

这代码我是按照教科书上写的,那教科书可能是按照VS2008的Beta版写的,是不是正式发行的LINQ有了一些改变?

跪清高人出手。。。。



------解决方案--------------------
HOHO。这个原因很简单因为楼主没有定义Customer表格的主键, LINQ没有这个信息就无法准确的更新数据库内的对象,所以把你的操作忽略了。

修改的方法是把CustomerId字段改为如下:
C# code

private int _customerId;

[Column(Storage = "_customerId", DbType = "Int NOT NULL", IsPrimaryKey = true)]
public int CustomerID
{
     get { return _customerId; }
     set
         {
           _customerId = value;
         }
}