本篇内容介绍了“Entity Framework主从表的增删改怎么实现”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!一、添加数据1
本篇内容介绍了“Entity Framework主从表的增删改怎么实现”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
在景点的住宿集合(Lodgings)中增加一个度假区(Resort)
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();
添加一个带两个住宿的景点
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();
添加一个带有景点信息度假村到住宿信息中。
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();}
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();
ForeignKeys方式:
var davesDump = (from l in context.Lodgings where l.Name == "HuangShan Hotel" select l).Single();davesDump.DestinationID = null;//(ForeignKeys方式)context.SaveChanges();
Reference方式:
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();
如果数据库里设置是级联删除,则不显示加载从表数据。
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();
删除主表数据,同时标注从表数据为删除状态(数据库关闭了级联删除的情况,可以手动去数据库的外键关系修改,也可以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(); //执行上面的所有标记
“Entity Framework主从表的增删改怎么实现”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!
--结束END--
本文标题: Entity Framework主从表的增删改怎么实现
本文链接: https://www.lsjlt.com/news/340812.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-28
2024-04-28
2024-04-28
2024-04-28
2024-04-28
2024-04-28
2024-04-28
2024-04-28
2024-04-28
2024-04-28
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0