Linq 到 Sql 问题
您好:我正在自学 C# 中的 Linq to Sql。因为我使用的是 SqlCE 数据库,所以我必须使用 SqlMetal 来生成 dbml 文件。一切顺利,我将 dbml 文件添加到我的程序中。我不知道如何为数据库生成 DataContext,但我可以查询数据库,但无法插入行。下面是一个不起作用的示例:
Journal 是数据库,Exercise 是数据库中唯一的表。
string con = Properties.Settings.Default.JournalConnectionString;
Journal db = new Journal(con);
Exercise ne = new Exercise();
ne.Date = Convert.ToDateTime("2009-10-25T14:35:00");
ne.Length = Convert.ToDouble(3.0);
ne.Elapsed = "00:53:35";
db.SubmitChanges();
有人可以建议我在插入时做错了什么吗?非常感谢。
Hello: I am teaching myself Linq to Sql in C#. Because I am using a SqlCE database I had to use SqlMetal to generate the dbml file. This went fine, and I added the dbml file to my program. I can't find out how to generate a DataContext for the database, but I can query the database, but can not insert a row. Here is an example of what does not work:
Journal is the Database, Exercise is the only table in the database.
string con = Properties.Settings.Default.JournalConnectionString;
Journal db = new Journal(con);
Exercise ne = new Exercise();
ne.Date = Convert.ToDateTime("2009-10-25T14:35:00");
ne.Length = Convert.ToDouble(3.0);
ne.Elapsed = "00:53:35";
db.SubmitChanges();
Can someone suggest what I am doing wrong with the insert? Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
可能还想查看 PLINQO 。它确实为 LINQ to SQL 添加了很多功能,并消除了很多痛点。
http://www.plinqo.com/
May want to check out PLINQO as well. It really adds a LOT of features to LINQ to SQL and takes away a lot of the pain points.
http://www.plinqo.com/
添加该行。
您应该在执行 SubmitChanges 之前
You should add the line
before doing SubmitChanges.
您需要告诉上下文插入您的对象。例如:
You need to tell the context to insert your object. For example:
要生成 DataContext,您需要使用 SqlMetal.exe 运行两个不同的命令。
这是我一直在使用的一个批处理文件,希望对您有所帮助:
您需要修改
.\SQLEXPRESS
以映射到您的数据库服务器。您的插入尝试的问题在于您正在创建要插入的对象,但实际上并没有告诉 LinqToSql 插入它。您需要在数据上下文上调用
InsertOnSubmit()
。To generate the DataContext, you need to run two different commands with SqlMetal.exe.
Here's a batch file I've been using that will hopefully help you out:
You'll need to modify
.\SQLEXPRESS
to map to your database server.The problem with your insert attempt is that you're creating the object you want to insert, but you're not actually telling LinqToSql to insert it. You need to call
InsertOnSubmit()
on your data context.您忘记将记录添加到表中。
既然您正在学习这一点,那么使用
using
也是一个好主意You forgot to add the record, to the table.
Since you are learning this, its also a good idea to use
using
您从未调用过
DataContext.InsertOnSubmit
:如果您想插入多个
练习
,请使用DataContext.InsertAllOnSubmit
:You never invoked
DataContext.InsertOnSubmit
:If you want to insert multiple
Exercise
s useDataContext.InsertAllOnSubmit
: