很久没用过EF了,最近换了公司,用的是EF框架,的确已经忘记了EF很多东西,虽说EF这东西性能不太好,但是可以满足我们的快速开发,在新的项目中我遇到了操作中间表的问题,我记得大学的时候用过,但是年代久矣,那时候又没有写博客的习惯,现在就写下来,以防又忘记了。
言归正传:
EF中间表是隐藏起来的,在EF可视化视图里面是看不到这个东东的。只能在数据库里面看到。
一共有3张表,如图下:
Orders表是订单表,Product是商品表,Orders_Product是中间表.
创建EF模型我就不说了,这个就略过了。
下面就开始操作中间表
一:新增:
public static void CreateFullOrdersByProduct() { using (var dbcontext = new TestEntities()) { var order = new Orders { OrderTitle = "购买汽车", CustomerName = "sss", TransactionDate = DateTime.Now, Product = new List<Product>() }; var employee1 = new Product { PName = "ss", Orders = new List<Orders>() }; var employee2 = new Product { PName = "sss", Orders = new List<Orders>() }; dbcontext.Orders.Add(order); order.Product.Add(employee1); dbcontext.SaveChanges(); } }
二:删除
public static void EmptyOrdersProduct() { using (var dbcontext = new TestEntities()) { //获取Product为1的所有Orders所有的信息 var producttoUpdate = dbcontext.Product.Include("Orders").FirstOrDefault(x => x.ID == 1); if (producttoUpdate != null) { producttoUpdate.Orders = new List<Orders>(); dbcontext.SaveChanges(); } else { Console.WriteLine("查询失败"); } } }
//这也是新增
public static void AddOrdersProduct() { using (var dbcontext = new TestEntities()) { var product = dbcontext.Product.Include("Orders").FirstOrDefault(x => x.ID == 2); int[] orderList = { 13, 14, 15, 16, 17, 18, 19 }; if (product != null) { var productOrder = new HashSet<int>(product.Orders.Select(x => x.ID)); foreach (var item in dbcontext.Orders) { if (productOrder.Contains(item.ID)) { //打印出重复的orderid Console.WriteLine("重复的id为" + item.ID); Console.WriteLine("不执行添加结果"); } else { //打印出Employee表中没有id Console.WriteLine($"即将添加的值:{item.ID}"); product.Orders.Add(item); } } } else { Console.WriteLine("product为空"); } dbcontext.SaveChanges(); } }
三:删除和修改
public static void UpdateInfoProductOrders() { using (var dbcontext = new TestEntities()) { int[] orderIdList = { 13, 14, 15, 16, 17, 18, 19 }; var productOrders = dbcontext.Product.Include("Orders").FirstOrDefault(x => x.ID == 2); if (productOrders != null) { //获取product中的OrderList var productOrderList = new HashSet<int>(productOrders.Orders.Select(e => e.ID)); foreach (var order in dbcontext.Orders) { if (orderIdList.Contains(order.ID)) { //判断要修改的orderid和orders表中的均包含 if (!productOrderList.Contains(order.ID)) { Console.WriteLine($"修改对应的订单Id表{order.ID}"); productOrders.Orders.Add(order); } } else { if (productOrderList.Contains(order.ID)) { Console.WriteLine($"删除无用的订单表{order.ID}"); productOrders.Orders.Remove(order); } } } } else { Console.WriteLine("查无的信息"); } dbcontext.SaveChanges(); }