所需工具:
C++
聪明的大脑文章源自灵鲨社区-https://www.0s52.com/bcjc/cyyjc/12493.html
勤劳的双手文章源自灵鲨社区-https://www.0s52.com/bcjc/cyyjc/12493.html
文章源自灵鲨社区-https://www.0s52.com/bcjc/cyyjc/12493.html
注意:本站只提供教程,不提供任何成品+工具+软件链接,仅限用于学习和研究,禁止商业用途,未经允许禁止转载/分享等文章源自灵鲨社区-https://www.0s52.com/bcjc/cyyjc/12493.html
文章源自灵鲨社区-https://www.0s52.com/bcjc/cyyjc/12493.html
教程如下
一、添加数据
1、在主表中添加从表数据
在景点的住宿集合(Lodgings)中增加一个度假区(Resort)文章源自灵鲨社区-https://www.0s52.com/bcjc/cyyjc/12493.html
[php]
var dest = (from d in context.Destinations where d.Name == "Bali" select d).Single();文章源自灵鲨社区-https://www.0s52.com/bcjc/cyyjc/12493.html
var resort = new CodeFirst.Model.Resort
{
Name = "Pete's Luxury Resort",
};文章源自灵鲨社区-https://www.0s52.com/bcjc/cyyjc/12493.html
dest.Lodgings.Add(resort);
context.SaveChanges();
[/php]文章源自灵鲨社区-https://www.0s52.com/bcjc/cyyjc/12493.html
2、添加主表的同时添加从表数据
添加一个带两个住宿的景点文章源自灵鲨社区-https://www.0s52.com/bcjc/cyyjc/12493.html
[php]
var destination = new CodeFirst.Model.Destination
{
Name = "AnHui HuangShan",
Lodgings = new List
{
new CodeFirst.Model.Lodging {Name="HuangShan Hotel"},
new CodeFirst.Model.Lodging {Name="YingKeSong Hotel"}
}
};
context.Destinations.Add(destination);
context.SaveChanges();
[/php]
3、添加从表的同时添加主表数据
添加一个带有景点信息度假村到住宿信息中。
[php]
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();
}
[/php]
二、修改关联
1、修改从表的外键
[php]
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();
[/php]
2、从表与主表脱离关系
1、ForeignKeys方式:
[php]
var davesDump = (from l in context.Lodgings where l.Name == "HuangShan Hotel" select l).Single();
davesDump.DestinationID = null;//(ForeignKeys方式)
context.SaveChanges();
[/php]
2、Reference方式:
[php]
var davesDump = (from l in context.Lodgings where l.Name == "HuangShan Hotel" select l).Single();
context.Entry(davesDump).Reference(l => l.Destination).Load(); //找主表数据
davesDump.Destination = null; //清空,(Reference方式)
context.SaveChanges();
[/php]
三、删除关联数据
1、删除主表的同时删除相关联的从表数据(级联删除)
如果 数据库里设置是级联删除,则不显示加载从表数据。
[php]
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();
[/php]
2、普通删除
删除主表数据,同时标注从表数据为删除状态(数据库关闭了级联删除的情况,可以手动去数据库的外键关系修改,也可以Fluent API配置关闭级联删除)
[php]
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(); //执行上面的所有标记
[/php]
评论