Saving Data

Adding an Entity

The example shows how to persist an entity to the database. Here we are creating a new user and also creating a new account and setting the user account property with the newly created account entity.

            Entities entities = new Entities();

            var user = new User();
            user.Firstname = "Mark";
            user.Lastname = "Johnson";
            user.Designation = "IT Manager";
            user.Account = new Account();
            user.Account.Status = "Active";
            user.Account.Username = username;
            user.Account.Password = hashedPassword;
            
            entities.AddObject(user);
            entities.SaveChanges();

In this example a Tenant is created and a new Project is also added to the list of Tenant Projects.

            Entities entities = new Entities();
            var tenant = new Tenant();
            tenant.Url = "http://home.example.com";
            
            var project = new Project();
            project.Name = "Testing";
            
            tenant.Projects.Add(project);

            entities.AddObject(tenant);
            entities.SaveChanges();

Modifying an Entity

To make changes to an entity, the entity has to be loaded into the context before any modifications can be saved on it. The example shows the user object being retrieved from the database and modifications being made to the user designation field.

            Entities entities = new Entities();
            var user = entities.User.Single(usr => usr.Id == 54);
            user.Designation = "Sr. IT Manager";
            entities.SaveChanges();