简体   繁体   中英

How does adding a record in db using Linq to SQL work?

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 Linq ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM