I am just learning Linq to SQL and from an example I added a record in db by passing a custom type object. For example to add a new user in users table I did:
db.Users.InsertOnSubmit(newUser);
db.SubmitChanges();
I couldn't get how Linq know which property value should be added in which column ?
Is there any better way then this to add a new record in db using Li开发者_如何学编程nq ?
Kindly also mention how I can add if I am not using custom types (DTO) ?
so thanks for your precious time and sharing.
Your DBML file spells out how all your objects' properties are mapped to your DBMS. the database tables/views you add to the DBML causes corresponding classes to be created for you—like your Users
class—whose properties are decorated with attributes telling L2S how to handle all the ORM mappings
Under your DBML file should be a [whatever].designer.cs file that shows this. Here's a sample of what it should look like:
[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;
snip
[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();
}
}
}
etc
精彩评论