private static void DeleteNinja() { ////All in one block for a simple detete. //using (var context = new NinjaContext()) //{ // context.Database.Log = Console.WriteLine; // var ninja = context.Ninjas.FirstOrDefault(); // context.Ninjas.Remove(ninja); // context.SaveChanges(); //SQL deletes using key value of ninja. //} ////For more complex apps, you'll want to close the context in between retrieving and deleting. //Ninja ninja; //using (var context = new NinjaContext()) //First context is used for retieval only. //{ // context.Database.Log = Console.WriteLine; // ninja = context.Ninjas.FirstOrDefault(); //} ////Perform additional operations here. //using (var context = new NinjaContext()) //Second context is used to delete only. //{ // context.Database.Log = Console.WriteLine; // context.Ninjas.Attach(ninja); //Need to attach ninja to the context because this is a new context. // context.Ninjas.Remove(ninja); // context.SaveChanges(); //SQL deletes using key value of ninja. //} //Attaching to remove is wierd, so the folowing way is preferred over the previous. Ninja ninja; using (var context = new NinjaContext()) //First context is used for retieval only. { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.FirstOrDefault(); } //Perform additional operations here. using (var context = new NinjaContext()) //Second context is used to delete only. { context.Database.Log = Console.WriteLine; context.Entry(ninja).State = EntityState.Deleted; //Mark ninja record for deletion in the new context. context.SaveChanges(); //SQL deletes using key value of ninja. } }
private static void DeleteNinjaDisconned() { //For online application only NinjaDomain.Classes.Ninja ninja; using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.FirstOrDefault(); } using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; context.Ninjas.Attach(ninja); context.Entry(ninja).State = EntityState.Deleted; context.SaveChanges(); } }
private static void GraphQueryRetrive() { using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; //No loading:------------------------ //all this returns is ninja object---no weapons/equiip var ninja = context.Ninjas.FirstOrDefault(x => x.Name.StartsWith("Huboy")); //Eager loading:---------------------------------------------------------: //if you want equipment you gotta include it,with eagerloading DbSet //has method called include. Dont abuse eagerloading slows down db ninja = context.Ninjas.Include(x => x.EquipmentOwned) .FirstOrDefault(x => x.Name.StartsWith("Huboy")); //--------------------------------------------------------------------------------//// //explict loading :---------------------------------------------------------------- //if state is note specified eqipmnet dont load ninja = context.Ninjas.FirstOrDefault(x => x.Name.StartsWith("Huboy")); Console.WriteLine("ninja retrived : {0} , Equipment {1}", ninja.Name, ninja.EquipmentOwned.Count);//count 0 //eager loads collection explicitly context.Entry(ninja).Collection(x => x.EquipmentOwned).Load(); //has to be specified without lazy loading Console.WriteLine("ninja retrived : {0} , Equipment {1}", ninja.Name, ninja.EquipmentOwned.Count); //2 //-------------------------------------------------------------------------------------------------------// //Lazy loading ------------------------------------------------------------------------: // make equipment prop virtual EF does some magic and gets count //magic comes with a performence hit if your loading alot of stuff since EF //in a foreach it would multiply the trips to the database by 2 for each row //since the equipment coloum is being lazy loaded in advance //use sparengly: Console.WriteLine("ninja retrived : {0} , Equipment {1}", ninja.Name, ninja.EquipmentOwned.Count);//count 2 } }
/// <summary> /// Allows you to delete object from DB. /// Problem here is, that to delete an object from DB it's still /// two trips. First to get the id, second to delete an object /// based on that Id. A better idea would be to execute a /// stored procedure that would do it in one go. /// </summary> private static void DeleteNinja() { Ninja ninja; using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.FirstOrDefault(); } using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; //context.Ninjas.Attach(ninja); //context.Ninjas.Remove(ninja); context.Entry(ninja).State = EntityState.Deleted; context.SaveChanges(); } }
private static void SimpleNinjaGraphQuery() { using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; //1. Eager Loading : to request related data, include a method of DBSet.Include() retrieves all related data from DB in one call in advance.Ninja plus Equipment joins ninja data and equipment data: context.Ninjas.Include(n => n.Equipment).FirstOrDefault(n => n.Name == "ObiFive"); // one call to db //var ninja = context.Ninjas.Include(n => n.EquipmentOwned).FirstOrDefault(n => n.Name == "ObiFive"); //Explicit Loading: request related data on the fly. first ask for ninja then when it is back with it in memory ask for related collection, another call to db use Entry property to let the context know we want related data, Load() method triggers executes SELECT query immediately, //2 connections to db var ninja = context.Ninjas.FirstOrDefault(n => n.Name == "ObiFive"); context.Entry(ninja).Collection(n => n.EquipmentOwned).Load(); Console.WriteLine(ninja.Name); //3.Lazy Loading - related data loaded on demand, add virtual to List<NinjaEquipment> in Ninja class, property should be virtual // related data loading is delayed till you specify request for it. } }
private static void QueryAndUpdateNinjaDisconnected() { Ninja ninja; using (NinjaContext context = new NinjaContext()) { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.FirstOrDefault(); } ninja.ServedInOniwaban = (!ninja.ServedInOniwaban); using (NinjaContext context = new NinjaContext()) { context.Database.Log = Console.WriteLine; context.Ninjas.Attach(ninja); context.Entry(ninja).State = EntityState.Modified; context.SaveChanges(); } }
//private static void RetrieveDataWithStoredProc() //{ // using (var context = new NinjaContext()) // { // context.Database.Log = Console.WriteLine; // var ninjas = context.Ninjas.SqlQuery("exec GetOldNinjas").ToList(); // //foreach (var ninja in ninjas) // //{ // // Console.WriteLine(ninja.Name); // //} // } //} //LD useful in disconnected scenarios private static void DeleteNinja() { Ninja ninja; using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.FirstOrDefault(); //LD trip one to the db //context.Ninjas.Remove(ninja); //context.SaveChanges(); } using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; //context.Ninjas.Attach(ninja); //LD the Attach is done in default after that below we set "EntityState.Deleted" //context.Ninjas.Remove(ninja); context.Entry(ninja).State = EntityState.Deleted; context.SaveChanges(); //LD trip two to the db } }
private static void SimpleNinjaGraphQuery() { using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; //EXAMPLE of EAGER LOADING //var ninja = context.Ninjas.Include(n => n.EquipmentOwned) // .FirstOrDefault(n => n.Name.StartsWith("Kacy")); //EXAMPLE OF EXPLICIT LOADING var ninja = context.Ninjas .FirstOrDefault(n => n.Name.StartsWith("Kacy")); context.Entry(ninja).Collection(n => n.EquipmentOwned).Load(); Console.WriteLine("Ninja Retrieved: " + ninja.Name); } }
} //RetrieveDataWithStoredProc() private static void DeleteNinja() { Ninja ninja; using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.FirstOrDefault(); //context.Ninjas.Remove(ninja); //context.SaveChanges(); } using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; /* making the context aware of the ninja object(prevents the context from being seen as a new context by the EF) */ //context.Ninjas.Attach(ninja); //context.Ninjas.Remove(ninja); context.Entry(ninja).State = EntityState.Deleted; context.SaveChanges(); } //using } //Deleting a ninja from the database
} //QueryAndUpdateNinja() private static void QueryAndUpdateNinjaDisconnected() { Ninja ninja; //This piece of code respresents the service or API retrieving a Ninja using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.FirstOrDefault(); }//using ninja.ServedInOniwaban = (!ninja.ServedInOniwaban); using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; context.Ninjas.Attach(ninja); //checking the state context.Entry(ninja).State = EntityState.Modified; context.SaveChanges(); } //using } //QueryAndUpdateNinjaDisconnected()
private static void QueryAndUpdateNinjaDisconnected() { Ninja ninja; using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.FirstOrDefault(); } ninja.ServedInOniwaban = (!ninja.ServedInOniwaban); // The changes will never get excuted, if just use the SaveChanges. // Learn more in Entity Framework in the Enterprise using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; //context.Ninjas.Attach(ninja); context.Entry(ninja).State = EntityState.Modified; context.SaveChanges(); } }
private static void DeleteNinja() { Ninja ninja; using (var context = new NinjaContext()) { ninja = context.Ninjas.FirstOrDefault(); } using (var context = new NinjaContext()) { // the context is destroy so EF won't remember this ninja // you can either attach ninja, so EF can recall it context.Ninjas.Attach(ninja); context.Ninjas.Remove(ninja); // or you can use Entry method and set the state to delete context.Entry(ninja).State = EntityState.Deleted; context.SaveChanges(); } }
private static void SimpleNinjaGraphQuery() { using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; // USING THE INCLUDE METHOD ENABLES EAGER LOADING // BE CAREFUL WHEN USING TOO MANY INCLUDES FOR DEEP GRAPHS SINCE QUERY PERFORMANCE WILL DEGRADE var ninja = context.Ninjas.Include(n => n.EquipmentOwned) .FirstOrDefault(n => n.Name.StartsWith("Kacy")); } // LEVERAGE EXPLICIT LOADING IF YOU DON'T NEED THE GRAPH TILL LATER using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; var ninja = context.Ninjas .FirstOrDefault(n => n.Name.StartsWith("Kacy")); Console.WriteLine("Ninja Retrieved:" + ninja.Name); context.Entry(ninja).Collection(n => n.EquipmentOwned).Load(); } // LEVERAGE LAZY LOADING BY MARKING POCO FIELD WITH VIRTUAL KEYWORD // CALLING THE COUNT() METHOD ON EQUIPMENTOWNED WILL TRIGGER THE LOAD // ALL LOT OF FOLKS ARE NOT A BIG FAN OF LAZY LOADING, BETTER TO KNOW WHAT YOU'RE EXPECTING AND EXPLICIT LOAD WHAT YOU NEED using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; var ninja = context.Ninjas .FirstOrDefault(n => n.Name.StartsWith("Kacy")); Console.WriteLine("Ninja Retrieved: " + ninja.Name); Console.WriteLine("Ninja Equipment Cound: {0}", ninja.EquipmentOwned.Count()); } }
private static void QueryObjectInvoleWithMultipleTable() { using (var context = new NinjaContext()) { /* * - Include will go to equipment table and get data * using index key in ninja table * - This is eager loading : load data in advance */ var ninjas = context.Ninjas.Include(n => n.EquipmentOwned); /* * - or Explicit loading : you can load equipment data on the fly * - Entry : go back to database and look for that ninja * - Collection : find the equiment in the equipment table * - Load : explicit loading */ var ninja = context.Ninjas.FirstOrDefault(n => n.Name == "kieu lam"); context.Entry(ninja).Collection(n => n.EquipmentOwned).Load(); /* * Lazy load : only load when it needed * - to do lazy load, you only need to go to ninja class * and set EquipmentOwned property to virtual. * - This will cause EF to override some logic behind the scene * for lazy loading */ /* * Projection query : allow you to return only property that you needed * - It also able to access data from other table */ var projectionNinja = context.Ninjas .Select( nin => new { nin.Name, nin.EquipmentOwned, nin.Clan.ClanName }); } }
private static void QueryAndUpdateNinjaDisconnected() { Ninja ninja; using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.First(); } // change is made outside of a using/connection ninja.ServedInOniwaban = !ninja.ServedInOniwaban; using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; // note: need to attach and flag as modified as we changed the ninja outside of this context context.Ninjas.Attach(ninja); context.Entry(ninja).State = EntityState.Modified; context.SaveChanges(); } }
/// <summary> /// Simple query and update via different dBContexts /// </summary> private static void QueryAndUpdateDisconnected() { Ninja ninja = null; using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.FirstOrDefault(n => n.Name.ToLower().Contains("patrick")); ninja.DateOfBirth = DateTime.Today.AddYears(-60); } using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; //Without these lines EF has no way of knowing what has changed //the reason for this is it is a different context context.Ninjas.Attach(ninja); // observe this entity context.Entry(ninja).State = EntityState.Modified; // informing EF the state has changed context.SaveChanges(); // Call save changes } }
/// <summary> /// This is for disconnected apps like websites,api service. /// Take deep look at disconnected model this is just the surface /// Take EF enterpise course for patterns to solve data persistance /// </summary> private static void UpdateNinjaDisconnectedModel() { //----note: //object to be changed Ninja ninja; //-----note: //imaginge the server is retriving a client object and sending //it back to the client using (var context = new NinjaContext()) { context.Database.Log = Console.WriteLine; ninja = context.Ninjas.FirstOrDefault(); } //-------note: //change: imagine the client updates said object and sends it back ninja.ServedInObiOne = (!ninja.ServedInObiOne); //---------note: //updating = false : EF has no way of nowing the state of the object //All this does is reinsatiate the context and call save() //the resut is only the query gets executed but save changes doesnt: //has no clue of the history of ninja, using (var context = new NinjaContext()) { //DBcontext Log: context.Database.Log = Console.WriteLine; //--------note: //lets make aware of ninja for argument sake: //lets add said ninja object: EF will add without being aware of the //state of ninja.EF is not a human and will do what you tell it: //----------------code:-----------commeted out for reason above !!!!!!!! //context.Ninjas.Add(ninja); //-------note: //if we use the attach method (we say hey watch this data //But it still has no way of knowing the state of ninja object //and how it used to have a different value: //this would be usefull to use if the value being changed was underneath //the attach statment: context.Ninjas.Attach(ninja); //-------note:Entery state //So we have to make EF context aware of the state of the object state //This is a great way to force entity framework to update all of the object //only downside is it goes through all the coloums: context.Entry(ninja).State = EntityState.Modified; context.SaveChanges(); //reasources:--read more //--https://stackoverflow.com/questions/30987806/dbset-attachentity-vs-dbcontext-entryentity-state-entitystate-modified } }