Entity Framework Core 3.1 入门(六)一对一和多对多关系的增删改查
此入门教程是记录下方参考资料视频的过程,本例基于Entity Framework Core 3.1
开发工具:Visual Studio 2019
目录
Entity Framework Core 3.1 入门(八)在 ASP.NET Core 中配置 Entity Framework Core
多对多
创建多对多关系
- 方法一
public static void Func_20()
{
using var context = new DemoContext();
var gamePlayer = new GamePlayer
{
GameId = 1,
PlayerId = 3
};
//DbContext中并没有GamePlayer的DbSet,所以直接调用Add()方法
context.Add(gamePlayer);
var count = context.SaveChanges();
Console.WriteLine("==============");
Console.WriteLine(count);
}
- 方法二
public static void Func_20()
{
using var context = new DemoContext();
var game = context.Games.First();
//通过Game的GamePlayer导航属性添加GamePlayer
game.GamePlayers.Add(new GamePlayer
{
//只需要设置PlayerId,GameId在此处自带,也可以手动设置
PlayerId = 4
});
var count = context.SaveChanges();
Console.WriteLine("==============");
Console.WriteLine(count);
}
删除多对多关系
public static void Func_21()
{
using var context = new DemoContext();
//其实gamePlayer应该是从数据库中查出来
var gamePlayer = new GamePlayer
{
GameId = 1,
PlayerId = 4
};
context.Remove(gamePlayer);
var count = context.SaveChanges();
Console.WriteLine("==============");
Console.WriteLine(count);
}
修改多对多关系
public static void Func_22()
{
using var context = new DemoContext();
//联合主键不能用EF Core修改,可以用SQL语句来修改
//应该先删除,再建立新的关系
var gamePlayer = new GamePlayer
{
GameId = 1,
PlayerId = 3
};
//删除属性
context.Remove(gamePlayer);
//修改属性
//...这里省略修改gamePlay的代码
//添加
context.Add(gamePlayer);
var count = context.SaveChanges();
Console.WriteLine("==============");
Console.WriteLine(count);
}
一对一
创建一对一关系
public static void Func_23()
{
using var context = new DemoContext();
var player = context.Players.First();
//通过导航属性添加
player.Resume = new Resume
{
Description = "1234"
};
var count = context.SaveChanges();
Console.WriteLine("==============");
Console.WriteLine(count);
}
模拟前端数据传递到后端(AsNoTracking(),数据离线)
public static void Func_24()
{
using var context = new DemoContext();
var player = context.Players.AsNoTracking()
.OrderBy(x => x.Id)
.Last();
player.Resume = new Resume
{
Description = "4321"
};
{
using var newContext = new DemoContext();
newContext.Attach(player);
var count = newContext.SaveChanges();
Console.WriteLine("==============");
Console.WriteLine(count);
}
}
修改一对一关系
错误案例
public static void Func_25()
{
var player = context.Players
.AsNoTracking()
.OrderBy(x => x.Id)
.Last();
player.Resume = new Resume
{
Description = "123456789"
};
{
using var newContext = new DemoContext();
newContext.Attach(player);
//因为PlayerId已经存在,且有唯一索引,所以使用Attach会报异常
var count = newContext.SaveChanges();
Console.WriteLine("==============");
Console.WriteLine(count);
}
}
正确案例
public static void Func_25()
{
using var context = new DemoContext();
var player = context.Players
.Include(x => x.Resume)
.OrderBy(x => x.Id)
.Last();
//有Include()追踪数据才能这样修改,没有Include()会报错
player.Resume = new Resume
{
Description = "123456789"
};
//会先删除原先的Resume数据,再添加
var count = context.SaveChanges();
Console.WriteLine("==============");
Console.WriteLine(count);
}