Unity Framework Cheat Sheet

A cheat sheet in English by mrtgr

This cheat sheet designed for unity custom framework

6,950 views 2,011 downloads 28 Dec 2017 History
3.7 avg · 0 ratings

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 Single­OrD­efault 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 Dynami­cQu­eryable 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 UnitOfWork if you want to add, edit or delete.

Badges

Nice Cheat Sheet

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.