LINQ to SQL 建立实体类
1、使用LINQ to SQL 建立实体类
使用LINQ to SQL时,需要首先建立用于映射数据库对象的模型,也就是实体类。在运行时,LINQ to SQL 根据LINQ表达式或查询运算符生成SQL语句,发送到数据库进行操作。数据库返回后,LINQ to SQL负责将结果转换成实体类对象。
建立实体类的方法有很多,例如LINQ to SQL设计器,手动编码建立,使用XML文件映射,使用命令行工具SqlMetal生成等。其中最方便的就是LINQ to SQL设计器。
在一个示例用的Demo控制台程序中添加一个“基于服务的数据库”Database1.mdf,建立一张tb_GuestInfo的表。该表的详细如下:
在项目中添加一个LINQ to SQL类,采用默认的名称DataClasses1.dbml,如下:
将Student表拖到界面上,保存。
相关代码如下:
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.1026
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebApplication1
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="StuMarks")]
public partial class DataClasses1DataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
#region 可扩展性方法定义
partial void OnCreated();
partial void InsertStudent(Student instance);
partial void UpdateStudent(Student instance);
partial void DeleteStudent(Student instance);
partial void InsertStuMark(StuMark instance);
partial void UpdateStuMark(StuMark instance);
partial void DeleteStuMark(StuMark instance);
#endregion
public DataClasses1DataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["StuMarksConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
public DataClasses1DataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public DataClasses1DataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
public DataClasses1DataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public DataClasses1DataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public System.Data.Linq.Table<Student> Student
{
get
{
return this.GetTable<Student>();
}
}
public System.Data.Linq.Table<StuMark> StuMark
{
get
{
return this.GetTable<StuMark>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Student")]
public partial class Student : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _id;
private string _name;
private EntitySet<StuMark> _StuMark;