我刚刚学习 Linq to SQL,从一个示例中,我通过传递自定义类型对象在 db 中添加了一条记录。例如,要在用户表中添加新用户,我做了:
db.Users.InsertOnSubmit(newUser);
db.SubmitChanges();
我不明白 Linq 如何知道应在哪列中添加哪个属性值?
还有比这更好的方法使用 Linq 在数据库中添加新记录吗?
还请提及如果我不使用自定义类型 (DTO),我该如何添加?
非常感谢您宝贵的时间和分享。
最佳答案
您的 DBML 文件详细说明了所有对象的属性如何映射到 DBMS。添加到 DBML 的数据库表/ View 会导致为您创建相应的类(例如您的 Users
类),其属性用告诉 L2S 如何处理所有 ORM 映射的属性进行修饰
在您的 DBML 文件下应该有一个 [whatever].designer.cs 文件来显示这一点。下面是它应该是什么样子的示例:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Invoices")]
public partial class Invoice : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private long _InvoiceId;
private string _InvoiceNum;
private decimal _TotalTaxDue;
剪
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_InvoiceId", AutoSync=AutoSync.OnInsert, DbType="BigInt NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public long InvoiceId
{
get
{
return this._InvoiceId;
}
set
{
if ((this._InvoiceId != value))
{
this.OnInvoiceIdChanging(value);
this.SendPropertyChanging();
this._InvoiceId = value;
this.SendPropertyChanged("InvoiceId");
this.OnInvoiceIdChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_InvoiceNum", DbType="VarChar(15)")]
public string InvoiceNum
{
get
{
return this._InvoiceNum;
}
set
{
if ((this._InvoiceNum != value))
{
this.OnInvoiceNumChanging(value);
this.SendPropertyChanging();
this._InvoiceNum = value;
this.SendPropertyChanged("InvoiceNum");
this.OnInvoiceNumChanged();
}
}
}
等等
关于c# - 如何使用 Linq to SQL 在数据库中添加记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5639696/