SubmitChanges并不总是更新数据库

时间:2012-09-15 14:27:21

标签: asp.net-mvc linq-to-sql sql-server-2008-r2

我正在使用带有LINQ-to-SQL和SQL Server 2008 R2的ASP.NET MVC 4(.NET framework 4.5)

如果我通过调试模式运行它,则此函数返回true,但是当我在没有调试的情况下运行它时,它返回false。我曾经遇到过这个错误:http://i.imgur.com/HydhT.png

我尝试使用谷歌搜索,出现了一些类似的问题,但我检查了所有问题:

  • UserProfiles表有一个主键
  • datacontext与数据库同步
  • 我尝试将 ConflictMode.ContinueOnConflict 作为参数提交给SubmitChanges()
  • 我试图将LINID设计器中的facebookID放在上面: UpdateCheck = UpdateCheck.Never

没有任何作用。我之前从未经历过这样的事情。有没有人有任何想法?

代码:

SQL Server中的

facebookID字段为varchar(50)NULL,默认值为NULL

public static bool changeFacebookIDByEmail(string email, string facebookID)
{
    UserProfile profile = (from s in _dc.Users
                           join u in _dc.Memberships on s.UserId equals u.UserId
                           join i in _dc.UserProfiles on u.UserId equals i.userID
                           where u.Email == email
                           select i).SingleOrDefault();

    profile.facebookID = facebookID;

    ChangeSet cs = _dc.GetChangeSet();

    _dc.SubmitChanges();

    if (cs.Updates.Count <= 0)
        return false;
    else
        return true;
}

2 个答案:

答案 0 :(得分:1)

您似乎正在执行手动SQL语句:

UPDATE UserProfiles SET facebookID = NULL WHERE userID = '85A6D951-15C8-4892-B17D-BD93F3D0ACBB'

这会将facebookID设置为null。但实体框架并不知道这一点。它无法解释原始SQL。所以它仍然认为facebookID设置为某个值。当你稍后在changeFacebookIDByEmail中将其设置为该值时,EF认为没有任何改变。

你可能不应该执行原始SQL字符串。使用EF将值更改为null。

答案 1 :(得分:0)

将.singleordefault改为.single我认为你的问题很快就会泄露出来。

基本上查询找到的任何内容都在datacontext中。任何新的,例如默认不会。

您需要重写例程,以便在未找到新用户的情况下插入新用户。

修改

这是我一直在研究的项目中的一些代码。我已经删除了很多东西来证明它应该如何工作。

// add the identity as necessary
var found = dB.Identities.SingleOrDefault(q => q.UserName == userName);

if (found == null)
{
    found = new Identity
    {
        Domain = domain,
        Password = User.Identity.AuthenticationType,
        Salt = "",
        UserName = userName,
        LastUpdatedDateTime = DateTime.Now
    };

    dB.Identities.InsertOnSubmit(found);
}



dB.SubmitChanges(null);