public static void Testing() { using CFDbContext db = new CFDbContext(); ProjectManagement projMng = new ProjectManagement(db); //ProjectOption projOption = new ProjectOption //{ // ProjectCreatorId = 1, // Title = "Full of sugar juice", // Description = "We are NOT using stevia", // Category = "HealthNOT", // EndDate = DateTime.Now.AddDays(4), // Goal = 5000m, //}; //Project project = projMng.CreateProject(projOption); ////////////////////////////////////////// Console.WriteLine(projMng.TrackProgressByProjectId(1)); ////////////////////////////////////////// //var proj = projMng.FindProjectsByProjectCreator(1); //var trediProjects = projMng.SortProjectsByTrends(); }
public static void Testing() { using CFDbContext db = new CFDbContext(); PackageManagement pkMng = new PackageManagement(db); //PackageOption pkOption1 = new PackageOption //{ // ProjectId = 2, // Amount = 110m, // Reward = "2 sugars", // Description = "Thanks for the support" //}; //PackageOption pkOption2 = new PackageOption //{ // ProjectId = 2, // Amount = 360m, // Reward = "6 sugars", // Description = "Thanks for the support, we love you a lot" //}; //Package package1 = pkMng.CreatePackage(pkOption1); //Package package2 = pkMng.CreatePackage(pkOption2); List <Package> packages = pkMng.FindPackagesByProjectId(1); foreach (Package p in packages) { Console.WriteLine($"Option ammount: {p.Amount} and reward: {p.Reward}"); } }
public static void Testing() { using CFDbContext db = new CFDbContext(); BackerManagement bckMng = new BackerManagement(db); //CREATE BACKER: START //BackerOption bckOption = new BackerOption //{ // FirstName = "Giannhs", // LastName = "Giannou", // Email = "gi@hot", // Username = "******", // Password = "******", // Dob = DateTime.Now //}; //Backer backer = bckMng.CreateBacker(bckOption); //CREATE BACKER: END //BACKER FUND A PROJECT: START //ProjectManagement projMng = new ProjectManagement(db); //List<Project> projects = projMng.FindProjects(); //foreach (Project p in projects) //{ // Console.WriteLine($"Project Id = {p.Id}, Title = {p.Title}"); //} //Console.WriteLine("Please select a Project Id you want to fund"); //int projId = Convert.ToInt32(Console.ReadLine()); //PackageManagement pkMng = new PackageManagement(db); //List<Package> packages = pkMng.FindPackagesByProjectId(projId); //foreach (Package pk in packages) //{ // Console.WriteLine($"Package Id = {pk.Id}, Amount = {pk.Amount}"); //} //Console.WriteLine("Please select a Package Id with which you will fund the project"); //int pkId = Convert.ToInt32(Console.ReadLine()); //PackageFundOption pfOption = new PackageFundOption //{ // BackerId = 3, // PackageId = pkId, // ProjectId = projId //}; //bckMng.FundProject(pfOption); //BACKER FUND A PROJECT: END var projectsfunded = bckMng.FindProjectsFundedByBacker(3); }
public static void Testing() { using CFDbContext db = new CFDbContext(); ProjectStatusManagement psMng = new ProjectStatusManagement(db); ProjectStatusOption psOption = new ProjectStatusOption { Title = "Today is a beutiful day", ProjectId = 1 }; ProjectStatus ps = psMng.CreateProjectStatus(psOption); }
////Entity Framework Data Access Approaches / utilizing Database First Implementations //public void GenericDataAccessApproaches() //{ // EFDFEntities dbctx = new EFDFEntities(); // //Native SQL using SqlQuery() // var stud1 = dbctx.Students.SqlQuery("Select studentid, studentname, standardId from Student where studentname='Bill'").FirstOrDefault<Student>(); // Using Parameterized query. //string query = "SELECT * FROM Department WHERE DepartmentID = @p0"; //Department department = await db.Departments.SqlQuery(query, id).SingleOrDefaultAsync(); //IQueryable<EnrollmentDateGroup> = from student in db.Students // group student by student.EnrollmentDate into dateGroup // select new EnrollmentDateGroup() // { // EnrollmentDate = dateGroup.Key, // StudentCount = dateGroup.Count() // }; // SQL version of the above LINQ code. //string query = "SELECT EnrollmentDate, COUNT(*) AS StudentCount " // + "FROM Person " // + "WHERE Discriminator = 'Student' " // + "GROUP BY EnrollmentDate"; //IEnumerable<EnrollmentDateGroup> data = db.Database.SqlQuery<EnrollmentDateGroup>(query); // ViewBag.RowsAffected = db.Database.ExecuteSqlCommand("UPDATE Course SET Credits = Credits * {0}", multiplier); // //ExecuteSqlCommnad() method is useful in sending non-query commands to the database // int noOfRowUpdated = dbctx.Database.ExecuteSqlCommand("Update student set studentname = 'changed student by command' where studentid = 1"); // int noOfRowInserted = dbctx.Database.ExecuteSqlCommand("insert into student(studentname) values('New Student')"); // int noOfRowDeleted = dbctx.Database.ExecuteSqlCommand("delete from student where studentid = 1"); // var stud2 = dbctx.Students.Find(1); // dbctx.Students.Add(stud2); // dbctx.Students.Remove(stud2); // //Can get DBEntityEntry object of a particular entity by using Entry method of DBContext // //to retrieve informations about the Entity // //-- Primarily usefull in Disconnected scenario[using same Dbcontext instance throughout the operation] // stud1.StudentName = "UpdatedName"; // dbctx.Entry(stud1).State = System.Data.Entity.EntityState.Added; // dbctx.Entry(stud1).State = System.Data.Entity.EntityState.Modified; // dbctx.Entry(stud1).State = System.Data.Entity.EntityState.Deleted; // //Parent Entity State Entity State of child entities // //Added Added // //Modified Unchanged // //Deleted All child entities will be null // dbctx.SaveChanges(); // //We can add properties in entity with attribute [NotMapped] which wont have impact on DBTable // //[NotMapped] // //public int NoteMappedpropertyinEntity { get; set; } // //RowVersion property /column in table generates unique binary number whenever the insert or update operation is performed in a table // //[Timestamp] // //public byte[] RowVersion { get; set; } // //For concurrent update , if there is conflict , it will throw DbUpdateConcurrencyException // //If Table created through Model , set concurrecy property to false // //Enum properties can be used // //public int GrnderEnumType{ Male=1,Female=2 }; // //public GrnderEnumType Gender {get;set;} // //Table - valued functions are similar to stored procedure with one key difference: // //the result of TVF is composable which means that it can be used in a LINQ query. // // USE[SchoolDB] // // GO // // /****** Object: UserDefinedFunction [dbo].[GetCourseListByStudentID] */ // // SET ANSI_NULLS ON // // GO // // SET QUOTED_IDENTIFIER ON // // GO // // CREATE FUNCTION[dbo].[GetCourseListByStudentID] // // ( // // --Add the parameters for the function here // // @studentID int // //) // // RETURNS TABLE // // AS // // RETURN // // ( // // --Add the SELECT statement with parameter references here // // select c.courseid, c.coursename, c.Location, c.TeacherId // // from student s left outer join studentcourse sc on sc.studentid = s.studentid left outer join course c on c.courseid = sc.courseid // // where s.studentid = @studentID // // ) // //Execute TVF and filter result // //var courseList = ctx.GetCourseListByStudentID(1).Where(c => c.Location.SpatialEquals(DbGeography.FromText("POINT(-122.360 47.656)")))) // // .ToList<GetCourseListByStudentID_Result>(); // //Eager Loading - Loads Child Entities by using Include() method on entity // //can also use linq lambda expression in Include method. For this, take a reference of System.Data.Entity namespace or else as string "Standard.Teachers" // var stud4 = dbctx.Students.Include(s => s.Standard.Teachers) // .Where(s => s.StudentName == "Student1") // .FirstOrDefault<Student>(); // //Lazy Loading - Loads Child Entities only when it is required through separate query // dbctx.Configuration.LazyLoadingEnabled = false;//Can be disabled and its subset of dbctx.Configuration.ProxyCreationEnabled = false; // //Loading students only // IList<Student> studList = dbctx.Students.ToList<Student>(); // //Loads Student address for particular Student only (seperate SQL query) // StudentAddress add = studList.ElementAtOrDefault<Student>(0).StudentAddress; // //Even with lazy loading disabled, it is still possible to lazily load related entities using Reference()/Collection() and Load() method // dbctx.Entry(stud4).Collection(s => s.Courses).Load(); // //Custom Entity validation at server side by override ValidateEntity method of DBContext - Reference Link http://www.entityframeworktutorial.net/EntityFramework4.3/validate-entity-in-entity-framework.aspx // try // { // using (var ctx = new EFDFEntities()) // { // ctx.Students.Add(new Student() { StudentName = "" }); // ctx.Standards.Add(new Standard() { StandardName = "" }); // ctx.SaveChanges(); // } // } // catch (DbEntityValidationException dbEx) // { // foreach (DbEntityValidationResult entityErr in dbEx.EntityValidationErrors) // { // foreach (DbValidationError error in entityErr.ValidationErrors) // { // Console.WriteLine("Error Property Name {0} : Error Message: {1}", // error.PropertyName, error.ErrorMessage); // } // } // } //} //We can take advantage of asynchronous execution of.Net 4.5 with Entity Framework.EF 6 has the ability to execute a query and command asynchronously using DbContext. //Asynchronous Query: private static async Task <CFStudent> GetStudent() { CFStudent myStudent = null; using (var context = new CFDbContext()) { Console.WriteLine("Start GetStudent..."); myStudent = await(context.CFStudents.Where(s => s.StudentID == 1).FirstOrDefaultAsync <CFStudent>()); Console.WriteLine("Finished GetStudent..."); } return(myStudent); //student.wait().This means that the calling thread should wait until the asynchronous method completes, so we can do another process, until we get the result from the asynchronous method. }
public static void Testing() { using CFDbContext db = new CFDbContext(); MediaManagement mediaMng = new MediaManagement(db); MediaOption mediaOption = new MediaOption { ProjectId = 1, Type = "Photo", URL = "myFace.png" }; Media media = mediaMng.CreateMedia(mediaOption); }
public static void Testing() { using CFDbContext db = new CFDbContext(); ProjectCreatorManagement pcMng = new ProjectCreatorManagement(db); ProjectCreatorOption pcOption = new ProjectCreatorOption { FirstName = "Nikos", LastName = "Nikou", Email = "nik@hot", Username = "******", Password = "******", Dob = DateTime.Now }; ProjectCreator pc = pcMng.CreateProjectCreator(pcOption); }
public ProjectCreatorManagement(CFDbContext _db) { db = _db; }
public BackerManagement(CFDbContext _db) { db = _db; }
public ProjectManagement(CFDbContext _db) { db = _db; }
public PackageManagement(CFDbContext _db) { db = _db; }
//Code First //Domain Driven Design public void CodeFirstHandler() { //Once Domain class and Context class is created , //if we instantiate the context class for any CRUD then the DB Objects will be created at first using (var ctx = new CFDbContext()) { CFStudent stud = new CFStudent() { StudentName = "New Student" }; ctx.CFStudents.Add(stud); ctx.SaveChanges(); } //Refer default Entity framework conventions on DB Object mapping - http://www.entityframeworktutorial.net/code-first/code-first-conventions.aspx //EF logs all the activity[Command queries] performed by EF using context.database.Log //Context.Database.Log is an Action<string> so that you can attach any method which has one string parameter and void return type.For example: //public class Logger //{ // public static void Log(string message) // { // Console.WriteLine("EF Message: {0} ", message); // } //} //using (var context = new CFDbContext()) //{ // context.Database.Log = Logger.Log; //} //public class MyLogger //{ // public void Log(string component, string message) // { // //Can pass on the same to Log4Net as Info // Console.WriteLine("Component: {0} Message: {1} ", component, message); // } //} //using (var context = new BlogContext()) //{ // var logger = new MyLogger(); // context.Database.Log = s => logger.Log("EFApp", s); // var blog = context.Blogs.First(b => b.Title == "One Unicorn"); // blog.Posts.First().Title = "Green Eggs and Ham"; // blog.Posts.Add(new Post { Title = "I do not like them!" }); // context.SaveChangesAsync().Wait(); //} //https://msdn.microsoft.com/en-us/library/dn469464(v=vs.113).aspx //Transaction Support //using (System.Data.Entity.DbContextTransaction dbTran = context.Database.BeginTransaction()) //{ // try // { //DbSet.AddRange/RemoveRange adds/remove collection(IEnumerable) of entities to the DbContext //CodeFirst SPROC //Inheritance Strategy in Code - First: not discissed in detail - http://www.entityframeworktutorial.net/code-first/inheritance-strategy-in-code-first.aspx }
public MediaManagement(CFDbContext _db) { db = _db; }