使Linq to SQL保存到数据库 [英] Get Linq to SQL to save to the database

查看:35
本文介绍了使Linq to SQL保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下代码:

 //获取当前用户_currentUser = WindowsIdentity.GetCurrent();//获取当前用户的地址列表_dataMap = new DataMapDataContext();_addresses = _dataMap.Addresses.where(address => address.InsertUserName == _currentUser.Name).ToList(); 

....

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

当我调用SubmitChanges时,数据库中什么也没有保存.这是为什么?我错过了重点吗?我认为使用linq to sql可以将项目添加到查询结果中,然后调用SubmitChanges,它将起作用.

如果您使用"ToList",它现在可以工作吗?如果不是,那么如何将东西插入收藏夹?(我不认为 Add 是 IQueryable 的一部分.)

解决方案

不要使用 _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.

这篇关于使Linq to SQL保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆