LINQ to SQL-插入新记录 [英] LINQ to SQL - Insert New Record
问题描述
我有一个带有自动递增ID字段的数据库表.该表通过实体数据模型通过代码公开.我正在尝试向该表中写入新记录.我有一种方法需要负责创建这些记录.此方法接受记录的属性值.它需要创建一条记录,并在另一个表中写入参考记录.当前,这是我正在尝试的
I have a database table with an auto-incrementing ID field. this table is exposed to by code via a Entity Data Model. I am trying to write a new record to this table. I have a method that needs to be responsible for creating these records. This method takes in the property values of the record. It needs to create a record, and write a reference record in another table. Currently, here is what I am trying
public int CreateRecord(string name, string description, List<int> ids)
{
using (DatabaseContext database = new DatabaseContext())
{
Record record = new Record();
record.Name = name;
record.Description = description;
database.Records.InsertOnSubmit(record);
database.SubmitChanges();
List<RecordTrack> tracks = new List<RecordTrack>();
foreach (int id in ids)
{
RecordTrack track = new RecordTrack();
track.RecordID = record.ID;
track.ID = id;
tracks.Add(track);
}
database.Tracks.InsertAllOnSubmit(tracks);
database.SubmitChanges();
}
}
我似乎无法以这种方式保存记录.当我通过要插入的Record时,我能够做到这一点.但是由于其他因素,我需要一种从头开始纯粹创建记录的方法.我在做什么错了?
I can't seem to get the record to save in this manner. I was able to do it when I passed a Record in that I wanted to insert. But due to other factors, I need a way to purely create the record here from scratch. What am I doing wrong?
谢谢!
推荐答案
在数据库上下文中应该有一个 AddToRecord()
函数.使用该函数添加 record
变量,然后从数据库上下文中调用 SaveChanges()
.
there should be a AddToRecord()
function in your database context. Use that function to add your record
variable and then call SaveChanges()
from your database context.
这篇关于LINQ to SQL-插入新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!