Show Menu
Cheatography

Unity Framework Cheat Sheet by

This cheat sheet designed for unity custom framework

FindById

var entity = entityRepository.FindById(entity.Id)

//Load with properties
var entity = entityRepository.FindById(entity.Id, x=> x.OtherEntity, t=>t.AnotherEntityCollection);
You can include properties with the query seperated by coma. This method calls FindAll with Singl­eOr­Def­ault method.

FindAll

//Parameterles.
entityRepository.FindAll();

//Get entities which SomeProperty = Predicate
entity.Repository.FindAll(x=>x.SomeProperty == "Predicate");

//Get entity and its Child Collection
entity.Repository.FindAll(x=>x.ChildCollection)

//Get entities which SomeProperty = Predicate and include Child Collection
entity.Repository.FindAll(x=>x.SomeProperty= "Predicate" , t=>t.ChildCollection);
You can extend search result with Dynam­icQ­uer­yable methods like where, select, skip, orderb­y,g­roupby etc.

Add

//Entity without a parent
entity = new entity() { ... };
entityRepository.Add(entity);

//Child object that has parent
entity = new entity() { ... , parentId= 3 };
entityRepository.Add(entity);
//OR
//Child Object that has parent
entity = new entity() { ... };
parent = parentRepository.FindyById(parentId);
parent.ChildEntityCollection.Add(entity);
You have 3 options. If entity doesn't have a parent, simply add with reposi­tory. Else if entity has parent you must set its parentId or set parents itself.
 

Remove

//With Entity Id
someModelRepository.Remove(entity.Id);

//With Entity
someModelRepository.Remove(entity);
This code will raises an error if entity has child object and relation in the DB doesn't cascade delete.

How to delete child object

//One-To-One Relation
parent.Child = null;

//One-To-Many Relation
parent.ChildCollection.Remove(Child);
//OR
parent.ChildCollection.Clear()
One-To­-Many Relations: Remember to mark parentId property in child entity with [Owner] attribute. Also in setter method of the parent navigation property, set parentId = 0 if value == null. If not, you'll get orphaned entity exception

UnitOfWork

try
{
    using (unitOfWorkFactory.Create())
    {
         //Add, Remove, Modify
    }
}
catch (ModelValidationException mvex)
{
    foreach (var error in mvex.ValidationErrors)
    {
        ModelState.AddModelError(error.MemberNames.FirstOrDefault() ?? "", error.ErrorMessage);
    }
}
You must use UnitO­fWork if you want to add, edit or delete.
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.