日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Entity?Framework主從表的增刪改_C#教程

作者:springsnow ? 更新時間: 2022-08-05 編程語言

一、添加數據

1、在主表中添加從表數據

在景點的住宿集合(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();

2、添加主表的同時添加從表數據

添加一個帶兩個住宿的景點

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();

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();
}

二、修改關聯

1、修改從表的外鍵

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();

2、從表與主表脫離關系

1、ForeignKeys方式:

var davesDump = (from l in context.Lodgings where l.Name == "HuangShan Hotel" select l).Single();
davesDump.DestinationID = null;//(ForeignKeys方式)
context.SaveChanges();

2、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();

三、刪除關聯數據

1、刪除主表的同時刪除相關聯的從表數據(級聯刪除)

如果數據庫里設置是級聯刪除,則不顯示加載從表數據。

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();

2、普通刪除

刪除主表數據,同時標注從表數據為刪除狀態(數據庫關閉了級聯刪除的情況,可以手動去數據庫的外鍵關系修改,也可以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();   //執行上面的所有標記

原文鏈接:https://www.cnblogs.com/springsnow/p/13230080.html

欄目分類
最近更新