LINQ to SQL support inserting data through object.
LINQ to SQL support inserting data through object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
namespace Linq2Sql_demo_doc
{
/// <summary>
/// Class to represent the SQL Server table
/// Emp
/// Id int
/// Name varchar(50)
/// </summary> ///
[Table(Name="Emp")]
public class Emp
{
//Comlumn mapping used from Data.Linq
[Column(IsPrimaryKey=true, IsDBGenerated=true)]
public int Id { get; set; }
[Column]
public string Name { get; set; }
}
//Class for the DataContext and List generation
public class TestDB : DataContext
{
public Table<Emp> Emps;
//Initializing base class constructor
public TestDB(string s) : base(s) { }
}
class Program
{
static void Main(string[] args)
{
string strConnection =
@"Data Source=.\sqlexpress;Initial Catalog=TestDB;";
TestDB db = new TestDB(strConnection);
Emp emp = new Emp();
emp.Name = "New Employee";
db.Emps.Add(emp);
db.SubmitChanges();
}
}
}
All the methods are coming from DataContext class (responsible for SQL query generation). The above method converts the object addition to DML query.
Namoskar!!!
Comments
Anonymous
July 13, 2007
LINQ to SQL support inserting data through object. using System; using System.Collections.Generic; usingAnonymous
July 16, 2007
LINQ to SQL support updating data through object. Continuing with my previous blog on INSERT , let meAnonymous
July 16, 2007
LINQ to SQL support deleting data through object. Continuing with my previous blog on INSERT , let meAnonymous
July 02, 2008
I tried the follwing code inorder to insert data into my database. Although it was successfully running, the table which is located in the database is not updated(after running the application, when I open the table, there is no data inserted). How can I solve these problem? Is there any settings need to be done??? UsersDBDataContext db = new UsersDBDataContext(); User a = new User(); a.UserName = "nSayoo"; a.Password = "124"; db.Users.InsertOnSubmit(a); db.SubmitChanges(); btw: I have username has a primary key.Anonymous
July 03, 2008
@nasayoo Code seems fine to me. What is the database are you using? use db.Log = Console.Out; to see the generated SQL statements. If you find an insert statement is getting generated then things should work fine.
- WRIJU
- Anonymous
September 23, 2008
The comment has been removed