1、根据主表添加从表数据

var dest = (from d in context.Destinations where d.Name == "Bali" select d).Single();

var resort = new CodeFirst.Model.Resort
{
Name = "Pete's Luxury Resort",
}; dest.Lodgings.Add(resort);
context.SaveChanges();

2、添加主表的同时添加从表数据

var destination = new CodeFirst.Model.Destination
{
Name = "AnHui HuangShan",
Lodgings = new List<CodeFirst.Model.Lodging>
{
new CodeFirst.Model.Lodging {Name="HuangShan Hotel"},
new CodeFirst.Model.Lodging {Name="YingKeSong Hotel"}
}
};
context.Destinations.Add(destination);
context.SaveChanges();

3、添加从表的同时添加主表数据

var resort = new CodeFirst.Model.Resort
{
Name = "Top Notch Resort and Spa",
Destination = new CodeFirst.Model.Destination
{
Name = "Stowe, Vermont",
Country = "USA"
}
};
using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
context.Lodgings.Add(resort);
context.SaveChanges();
}

4、修改从表的外键

var hotel = (from l in context.Lodgings where l.Name == "YingKeSong Hotel" select l).Single();
var reef = (from d in context.Destinations where d.Name == "Bali" select d).Single(); hotel.Destination = reef;
context.SaveChanges();

5、删除主从表关系

var davesDump = (from l in context.Lodgings where l.Name == "HuangShan Hotel" select l).Single();
davesDump.DestinationID = null;//(ForeignKeys方式) //context.Entry(davesDump).Reference(l => l.Destination).Load(); //找主表数据
//davesDump.Destination = null; //清空,(Reference方式)
context.SaveChanges();

6、删除主表的同时删除相关联的从表数据(级联删除)

var canyon = (from d in context.Destinations where d.Name == "AnHui HuangShan" select d).Single();

context.Entry(canyon).Collection(d => d.Lodgings).Load();  //显示加载
context.Destinations.Remove(canyon);
context.SaveChanges();

7、普通删除

删除主表数据,同时标注从表数据为删除状态(数据库关闭了级联删除的情况,可以手动去数据库的外键关系修改,也可以Fluent API配置关闭级联删除)

var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single();

foreach (var lodging in canyon.Lodgings.ToList())
{
context.Lodgings.Remove(lodging); //先标记相关的从表数据为删除状态
}
context.Destinations.Remove(canyon); //再标记主表数据为删除装填
context.SaveChanges(); //执行上面的所有标记
05-22 13:34