一、单表Reader
1 构建Reader类
public class Reader
{
public int ReaderID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Tel { get; set; }
}
2、构建数据上下文类
//单表数据上下文
public class SingleDbContext :DbContext
{
public DbSet<Reader> Readers { get; set; }
public SingleDbContext() : base("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=NewsDB;Data Source=.") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{//防止自动把表名改成了复数形式
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
}
3、在程序中测试
static void SingleTable()
{
///添加
var reader = new Reader
{
Name = "xp",
Age = 18,
Tel = "135993434"
};
var database = new SingleDbContext();
database.Readers.Add(reader);
int rows = database.SaveChanges();
//查询
using (var context = new SingleDbContext())
{
var readers = from r in context.Readers where r.Name == "xp" select r;
foreach (Reader r in readers)
Console.WriteLine("name:" + r.Name);
}
}
二 主从表
Department
Course
1 构建类
public class Department
{
public virtual ICollection<Course> Course { get; set; }
public int DepartmentID { get; set; }
public string Name { get; set; }
public string Tel { get; set; }
}
public class Course
{
// Primary key
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
// Foreign key
public int DepartmentID { get; set; }
// Navigationproperties
public virtual Department Department { get; set;}
}
二构建数据上下文
public class MasterSlaveDbContext: DbContext
{
public DbSet<Department> Department { get; set; }
public DbSet<Course> Course { get; set; }
public MasterSlaveDbContext() : base("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=NewsDB;Data Source=.") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{//防止自动把表名改成了复数形式
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.PluralizingTableNameConvention>();
}
}
三、测试使用
static void MasterSlaveTable()
{
///添加
var department = new Department
{
Name = "计算机科学学院",
Tel = "83031222"
};
var database = new MasterSlaveDbContext();
database.Department.Add(department);
int rows = database.SaveChanges();
var course = new Course
{
Title = "高数",
Credits = 4,
DepartmentID= department.DepartmentID//自动获取递增主键
};
database.Course.Add(course);
database.SaveChanges();
//查询
using (var context = new MasterSlaveDbContext())
{
var dp = from d in context.Department.Include("Course") where d.DepartmentID == 8 select d;
foreach (Department d in dp)
{
foreach (Course c in d.Course)
{
Console.WriteLine("name:" + c.Title);
}
}
}
}
源代码:http://download.csdn.net/detail/metal1/9855473