public static void UpdateEntity() { using (var context = new EFTestContext()) { var product = context.Products.FirstOrDefault(); Console.WriteLine($"Origin Data: {product.Name},{product.Money}"); product.Money = 299; context.SaveChanges(); Console.WriteLine($"After Update: {product.Name},{product.Money}"); } }
private static void OneToOne() { using (EFTestContext context = new EFTestContext()) { context.Database.Log = Console.WriteLine; var product = context.Products.Include(p => p.Book).First(); product.Book = new TBook { Page = 300 }; context.Entry(product).State = EntityState.Modified; context.SaveChanges(); } }
public static void EFDeleteAction() { using (var context = new EFTestContext()) { // EF Remove, RemoveRange是一筆一筆刪除 context.Database.Log = Console.WriteLine; var product = context.Products.FirstOrDefault(); context.Products.Remove(product); var products = context.Products.Where(p => p.PId > 1); context.Products.RemoveRange(products); context.SaveChanges(); } }
private static void OneToManyCutomFK() { using (EFTestContext context = new EFTestContext()) { context.Database.Log = Console.WriteLine; var userRole = context.UserRoles.First(); context.Users.Add(new TUser { Name = "Wendy", Account = "Wendy", Password = "******", UserRole = userRole }); context.SaveChanges(); } }
public static void EFInsertAction() { using (var context = new EFTestContext()) { context.Database.Log = Console.WriteLine; context.Products.Add(new TProduct { Name = "MVC 開發實戰", Money = 399, Category = "網頁開發" }); context.Products.AddRange(new List <TProduct> { new TProduct { Name = "Docker 入門實戰", Money = 399, Category = "容器" }, new TProduct { Name = "大話設計", Money = 399, Category = "設計模式" } }); context.SaveChanges(); } }
private static void OneToMany() { using (EFTestContext context = new EFTestContext()) { context.Database.Log = Console.WriteLine; var order = new TOrder { OrderDate = DateTime.Now, OrderDetails = new List <TOrderDetail> { new TOrderDetail { Price = 699, ProductName = "Design Pattern", Quantity = 1 }, new TOrderDetail { Price = 499, ProductName = "MVC In Action", Quantity = 1 } } }; context.Orders.Add(order); context.SaveChanges(); } }