且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使Linq to SQL保存到数据库

更新时间:2023-02-08 18:05:50

不要使用 _addresses.Add

您不能直接添加到IQueryable,需要将其添加到实体集.

尝试一下:

  _dataMap.Addresses.InsertOnSubmit(form.Item);_dataMap.SubmitChanges(); 

当然,我看不到 form.Item 是什么,但是请注意,它必须与 _dataMap.Addresses 实体集具有相同的实体类型

如果使用 .ToList() 没有区别.

使用LINQ-SQL(除非您使用某种POCO映射),您不能将项目添加到集合/查询中,您需要将项目直接添加到指定数据上下文的实体集中./p>

您可以根据需要多次调用 .InsertOnSubmit ,然后 .SubmitChanges 将为您将所有这些INSERT推送到数据库中.

有关 InsertOnSubmit 的更多信息,此处

So I have the following code:

// Get the current user
_currentUser = WindowsIdentity.GetCurrent();

// Get the list of address for the current user
_dataMap = new DataMapDataContext();
_addresses = _dataMap.Addresses
         .Where(address => address.InsertUserName == _currentUser.Name).ToList();

....

_addresses.Add(form.Item);
_dataMap.SubmitChanges();

When I call SubmitChanges nothing is saved in the database. Why is that? Am I missing the point? I thought with linq to sql you could just add items to your query results and then call SubmitChanges and it will work.... Clearly I am missing something.

Does it now work if you use "ToList"? If not then how do you insert stuff into the collection? (I don't think Add is part of IQueryable.)

Dont use _addresses.Add

You can't add directly to an IQueryable, you need to add it to the entity set.

Try this:

    _dataMap.Addresses.InsertOnSubmit(form.Item);
    _dataMap.SubmitChanges();

Of course, i can't see what form.Item is, but be aware it needs to be of the same Entity type as the _dataMap.Addresses entity set.

It makes no difference if you use .ToList().

With LINQ-SQL (unless you're using some sort of POCO mapping), you can't add items to a collection/query, you need to add the item directly into the Entity Set for the specified Data Context.

You can call .InsertOnSubmit as many times as you like, and .SubmitChanges will push all those INSERT's to the DB for you.

More info on InsertOnSubmit here.