我正在使用Linq to SQL,并通过添加一个.dbml文件来作为我的应用程序和SQL服务器之间的桥梁。我很好奇是否有一种不使用.dbml文件的方式来使用Linq to SQL?我偶然发现了这个链接,但是它不是很易懂。请问有人能够解释一下吗?注意:请不要修改HTML标记。
USE [businessLinqToSql]
GO
/****** Object: Table [dbo].[Customer] Script Date: 06/17/2016 11:28:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer](
[ID] [int] NOT NULL,
[Name] [nchar](30) NOT NULL,
[Address] [nchar](30) NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Customer.cs
的代码文件,如下所示。这将是您的POCO类,其中包含一些声明性属性,这些属性提供了有关数据库模式的提示,以供LINQ-to-SQL提供程序使用:[Table(Name="Customer")]
public class Customer
{
[Column(IsPrimaryKey = true)]
public int ID { get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Address { get; set; }
}
private static void LinqToSql()
{
DataContext dataContext = new DataContext("data source=.;initial catalog=businessLinqToSql;integrated security=True;MultipleActiveResultSets=True");
Table<Customer> customers = dataContext.GetTable<Customer>();
IQueryable<string> query = from c in customers
where c.Name.Length > 5
orderby c.Name.Length
select c.Name.ToUpper();
foreach (string name in query) Console.WriteLine(name);
}
context.TableName
)进行查询,则不行。TableAttribute
。这是手动复制dbml正在执行的操作。请参阅此链接了解更多信息。[Table]
public class Customer
{
[Column(IsPrimaryKey=true)]
public int ID;
[Column]
public string Name;
}
public class DemoDataContext : DataContext
{
public DemoDataContext (string cxString) : base (cxString) { }
public Table<Customer> Customers { get { return GetTable<Customer>(); } }
public Table<Purchase> Purchases { get { return GetTable<Purchase>(); } }
}
使用方法:
var db = new DataContext();
var customers = db.GetTable<Customer>();
var query = customers.Where (c => c.Name.StartsWith ("a"));