entity framework same model different tables - entity-framework

Problem: Save same kind of aggregated statistics for web api calls for different time units (hour, day etc.).
All the aggregated information will contain the same kind of information. Something along the lines of:
public class AggregatedStatistics
{
public DateTime TimeStamp { get; set; }
public int Hits { get; set; }
public int CachedHits { get; set; }
}
Since I would like to aggregate stats for different time units I would like to keep each time unit in a separate table. Reason being that it would a) make lookups faster and b) less risk of accidentally using wrong data. I am not experienced with databases so I do not know if either point really is a concern. I guess the latter should not be, and the former depends on the amout of data.
So, what is a good way to accomplish what I am after? I guess one solution that might work is to make the above class abstract and inherit from it (if that would work in EF Code First). That seems kind of semi-ugly though since no more members would be added to the class.

Related

Entity Framework context format

I'm just now learning MVC4 and Entity Framework. Some examples I have seen have all the "DbSet"s in one class, other I have seen each model have the DbSet in it. Is there an advantage of one way or the other? I kinda like having ONE "MyDbContext" model that references all the other models, but not sure which is better. Any thoughts and real life issues with either way?
public class UsersContext : DbContext
{
public DbSet<UserProfile> UserProfiles { get; set; }
}
public class UsersPostsContext : DbContext
{
public DbSet<UserPost> UserPosts { get; set; }
}
Verses:
public class MyContext : DbContext
{
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<UserPost> UserPosts { get; set; }
}
The first example is definitely not the way to go.
It defeats the power of EF to handle complex object graphs. What if you want to retrieve users and their posts and profiles from the database? (Just a random example). You'd need three contexts and a lot of cunning to put the right objects together. And that's only the reading part. CUD actions are even more complex, if only the logic you need to do inserts/deletes in the right order and set FK associations.
That does not necessarily mean that, consequently, you should always have one context class. It can be beneficial to have several of them for parts of the database that logically belong together and are relatively isolated from other parts (like authorization tables, CRM tables, product tables, reporting, ...). In this case you may decide to use bounded contexts.
I use the second notation because that context is more flexible to use. You don't have to wonder which object to pass to the service for example. You don't have to manage a numer of files so it is easier to understand database schema.

How do I handle persistence and unit of work in DDD using Entity Framework?

I'm a little overwhelmed with all of the information on DDD, unit of work, domain services, app services, etc. I'm trying to figure out how a persistence-ignorant domain model ultimately gets persisted, specifically in the context of unit-of-work and Entity Framework. Let's say I have an Order aggregate root, which I am attempting to keep in my persistence-ignorant domain model (the core of my architectural onion):
public class Order : EntityBase
{
public int Id { get; private set; }
public int MarketplaceId { get; private set; }
public int CustomerId {get; set;}
public List<OrderItem> Items { get; private set; }
public List<OrderComment> Comments { get; private set; }
public void AddItem(OrderItem item) { /**add item**/ }
public void AddComment(OrderComment comment) { /**add comment**/ }
public override bool Validate() { /**validate**/ }
public void Cancel() { /**cancel**/ }
}
Let's say I have a process that updates a property on the Order entity, for example it changes the CustomerId associated with the order.
I have an IOrderRepository in my domain layer, which would have an implementation (in an outer layer) with a function like this:
Order GetOrder(int orderId)
{
//get entity framework order, items, etc.
//map to domain-layer order and return domain-layer order
}
void UpdateOrder(Order order)
{
//get ENTITY FRAMEWORK order, order items, order comments, etc.
//take DOMAIN order (passed in to this function), and update EF items fetched above
//use a single EF unit of work to commit these changes
}
There's something wrong with my approach. The UpdateOrder function seems heavy for a small change; but it also seems I have to do that if my repository isn't aware of which items on the persistence-ignorant domain model have changed. Should I be handling every type of update in a separate repository function? UpdateMarketplace(int marketplaceId), UpdateCustomer(int customerId)?
As I'm typing this, I'm also wondering...maybe the way I have it above is not too heavy? If I change one property, even though I'm doing all of the above, perhaps Entity Framework will recognize that the values being assigned are the same and will only send the one db column update to SQL?
How can I take my Order domain model (fetching is straightforward enough), perform some operation or operations on it that may be limited in scope, and then persist the model using Entity Framework?
You need to look into the Unit of Work pattern. Your UoW keeps track of the changes, so when you get your order from your repository and modify it, you call UnitOfWork.SaveChanges() which should persist all the changes.
Using Entity Framework, your DbContext is basically the Unit of Work but I would create a simpler interface around it so you can abstract it away for easier usage in your higher layers.
Regarding EF, I would recommend mapping your domain entities directly using the code first approach. I would also turn off lazy loading and all the magic stuff so you have full control and less "surprises".
Unfortunately I'm not allowed to share our code but we have all this working pretty effectively with the new EF6 Alpha 3. I would recommend you taking a look at Microsoft Spain's nlayerapp for some implementation examples. I don't agree with many of their design decisions (also, see this review), but I think you can draw some inspiration from the Entity Framework parts. Take a look at their Unit of Work implementation and especially how they have abstracted it away for easier usage in the higher layers, and how they use it in their application services.
I will also recommend looking into creating a generic repository to avoid duplicating lots of logic in your aggregate specific repositories. MS Spain has one here, but you should also take a look at this thread.
Please have a look at this SO question where I gave an example of how I've implemented UoW & Repositories.
As #Tommy Jakobsen told you, your domain entities should be your EF entities, it would avoid you to add a useless mapping layer.
Hope that helps!
You may check ASP.NET Boilerplate's Unit Of Work implementation: http://www.aspnetboilerplate.com/Pages/Documents/Unit-Of-Work
It's open source project, you can check codes. Also, you can directly use it.

Building business logic on top of entity framework 5 POCOs

I've got an ADO.NET background and its the first time I've used Entity Framework in a serious project so I've gone ahead and got VS2012 and am using .NET 4.5 and entity framework 5.
I'm taking the data first approach and have created the database, generated the .edmx and also seperated out the POCOS from the context using this method: http://allen-conway-dotnet.blogspot.co.uk/2013/01/separating-entity-framework-poco.html
So my solution looks like this:
Data.Access (where I access the EF context and return POCOS to Business Layer)
Data.Model (where the POCOs are)
Data.Repository (where the context sites)
Presentation.Admin.Website
Now say I have the following table in the database / POCO class (just an example - not real)
namespace Data.Model
{
using System;
using System.Collections.Generic;
public partial class Car
{
public Car()
{
this.Parts= new HashSet<Parts>();
}
public int ID { get; set; }
public string Manufacturer { get; set; }
public string Model{ get; set; }
public Nullable<bool> Enabled { get; set; }
public virtual ICollection<Parts> Parts{ get; set; }
}
}
Now say all the cars in the database have an web service or even just a link to a URL which returns XML and gives me a list of available parts. The way in which each car retrieves the parts data is different (some are REST, some WCF, some from a CSV file, etc).
So I want to define classes that extend Car and define a "GetParts()" method which will have specific business logic to get parts for that particular car.
I also want to be able to get all cars from the database and loop them, calling the GetParts method for each one to retrieve the data.
I am thinking I need to define an interface or abstract class ICar declaring the GetParts method and somehow incorporating the Car POCO but getting confused about how to go about coding this.
Can anyone explain briefly how I can structure my code to get this done, perhaps suggesting a design pattern?
I'm taking the data first approach
The way in which each car retrieves the parts data is different (some
are REST, some WCF, some from a CSV file, etc).
Considering your type of data store is variable and you presumably want a reusable model then I think the choice of using EF database first is not a good one for you. Better to go with code first.
So I want to define classes that extend Car and define a "GetParts()"
method which will have specific business logic to get parts for that
particular car.
Your model should be persistence ignorant. I would not consider extending or hardcoding a data store specific GetParts() if that's what you are after.
perhaps suggesting a design pattern?
Perhaps look into using a repository to provide a layer of abstraction over your data mapping.

Executing logic before save or validation with EF Code-First Models

I'm still getting accustomed to EF Code First, having spent years working with the Ruby ORM, ActiveRecord. ActiveRecord used to have all sorts of callbacks like before_validation and before_save, where it was possible to modify the object before it would be sent off to the data layer. I am wondering if there is an equivalent technique in EF Code First object modeling.
I know how to set object members at the time of instantiation, of course, (to set default values and so forth) but sometimes you need to intervene at different moments in the object lifecycle.
To use a slightly contrived example, say I have a join table linking Authors and Plays, represented with a corresponding Authoring object:
public class Authoring
{
public int ID { get; set; }
[Required]
public int Position { get; set; }
[Required]
public virtual Play Play { get; set; }
[Required]
public virtual Author Author { get; set; }
}
where Position represents a zero-indexed ordering of the Authors associated to a given Play. (You might have a single "South Pacific" Play with two authors: a "Rodgers" author with a Position 0 and a "Hammerstein" author with a Position 1.)
Let's say I wanted to create a method that, before saving away an Authoring record, it checked to see if there were any existing authors for the Play to which it was associated. If no, it set the Position to 0. If yes, it would find set the Position of the highest value associated with that Play and increment by one.
Where would I implement such logic within an EF code first model layer? And, in other cases, what if I wanted to massage data in code before it is checked for validation errors?
Basically, I'm looking for an equivalent to the Rails lifecycle hooks mentioned above, or some way to fake it at least. :)
You can override DbContext.SaveChanges, do the fix up there and call into base.SaveChanges(). If you do that you may want to call DetectChanges before doing the fix up. Btw. the very same issue is discussed in Programming Entity Framework DbContext book (ISBN 978-1-449-31296-1) on pages 192-194. And yes, this is in context of validation...
You can implement IValidatableObject. That gives you a single hook:
IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
And you can apply your validation logic there.
There's also a SavingChanges event on ObjectContext (which you can obtain from the DbContext).
You could just create a custom IDoStuffOnSave interface and apply it to your entities that need to execute some logic on save (there's nothing out of the box)

How to update grandchildren in an aggregate root

I Use EF Code First, and lazy loading.
My problem relates to how to efficiently update an entity in within a grandchild collection. First of all, i fear this makes a lot of calls in the db that is not really needed. But if my domain class is not to care about persitance, I cant see another way to do this.
Here is the classes:
public class Supplier
{
public int Id {get;set;}
//...Supplier properties
public virtual ICollection<Contract> Contracts {get;set;}
//supplier methods
}
public class Contract
{
public int id {get;set;}
public int SupplierId{get;set;}
//---Contract properties
[ForeignKey("SupplierId")]
public virtual Supplier Supplier {get;set;}
public virtual ICollection<DeliveryContract> DeliveryContracts {get;set;}
}
public class DeliveryContract
{
public int Id {get;set;}
public bool DeliveryOnMonday{get;set;}
public bool DeliveryOnTuesday{get;set}
//...30 different Delivery terms properties
public Department Department {get;set;}
public int ContractId {get;set;}
[ForeignKey("ContractId")
public virtual Contract Contract {get;set;}
}
The Supplier is the aggregate Root. So i have a method on the supplier which is ChangeDeliveryContract, and that corresponds to what would happen in the real world.
public class Supplier
{
//properties
public void ChangeDeliveryContract (DeliveryContract cahangedDc)
{
//So from the supplier i have to find the contract to change
var dcToUpdate = Contracts
.SingleOrDefault(c=>c.Id == changedDc.ContractId)
.SingleOrDefalut(dc=>dc.Id == changedDc.Id);
//So... what do i do now? Map all 30 properties from changedDc to DcToUpdate
//Some business rules is also applied here i.e. there can only be one
// DeliveryContract between Supplier and Department
}
}
I use MVC so the program would look something like:
public ActionResult Update (DeliveryContract changedDc, int supplierId)
{
var Supplier = supplierRepository.GetById(supplierid);
supplier ChangeDeliveryContract (changedDc);
supplierRepository.Save();
//More code...
}
First of all, the problem lays in the ChangeDeliveryContract. I've not been able to get this to work. Also, i feel querying through collections like I do might be inefficient. Third, mapping 30 + properties also feels a bit wrong.
How do you guys do it, and is there a best practices here.
In applying DDD, the selection of aggregate roots can vary depending on various characteristics of the model, which include considerations regarding the number of children, etc. In this case, while Supplier is an AR, it does not mean that DeliveryContract can't also be an AR. While it may seem like Supplier is the sole AR and all operations regarding suppliers should stem from the Supplier class, this can become unruly with respect to database calls as you've come to realize. One role of an AR is the protection of invariants and there is nothing on the Supplier class that is used to protecting invariants which is a possible indication that Supplier is not the most appropriate AR to implement the required business rules. Therefore, it seems to me that in this case you can make DeliveryContract an AR, with its own repository, and a method for applying changes. Or you can make Contract an AR, depending on whether a contract must enforce any invariants regarding delivery contracts and also on a practical consideration of the number of expected delivery contracts per contract. If the number is very high, then it would be impractical to have a collection of delivery contracts on the contract class. Overall, I would opt for having smaller ARs, though invariants and consistency rules must be considered.
Take a look at a great series of articles by Vaughn Vernon for an in-depth treatment of this topic: Effective Aggregate Design.
OK, this is a bit confusing and I blame it on the mixing of the Domain and Persistence models(yeah, those EF tutorials have done a GREAT job of confusing everyone). One should not influence another, that's why you have the repository pattern. And yes, the domain should not care about the persistence.
Now that the Suplier doesn't know about EF anymore, let'see... If I understand correctly then you prety much need to redesign the Supplier (and probably the children aggregates as well) because you need to take into account the business rules.
It's pretty hard for me to reverse engineer the requirements from that code, but I have a feeling that a supplier has delivery contracts to different departments. When you change a delivery contract the supplier should enforce the business rules valid in that context (that's important if there are multiple contexts valid for the same entity).
I think though the delivery contract needs a bit more clarification, because I can't believe it's only a dumb object that only holds 30 properties. Perhaps some business rules are tied to some properties? So, we need more details.
As a side, if your really need to map 30 properties brcause that's the way it is, you can use Automapper for that.
About the property mapping in ChangeDeliveryContract, you feel like mapping 30 properties is a bit wrong. In itself there's nothing wrong with mapping 30 properties. If it has to be done, it has to be done. You could use AutoMapper for it, to ease the task.
I think the 'feel' of the code can be changed if you make methods like 'Supplier.MakeDeliveryOnMonday()', 'Supplier.DontMakeDeliveryOnTuesday()'. You probably can guess what these methods do (check business logic and set a boolean to true or false). So you don't have to use 'big' methods like ChangeDeliveryContract.