Onion Architecture- Entity Framework Code First Models DataAnnotations - entity-framework-5

I am developing a ASP.NET MVC Project following the Onion Architecture. I have added the Models inside my Core Project and these Models will be referred as the POCO classes for the Entity Framework Models in the Infrastructure Project.
My question is how can I add Data Annotations Which depends on the Entity Framework?
Can I make the Core Models as Interfaces and inherit it in the Infrastructure Projects and do real Implementation?

You don't need to create Core Models as Interfaces if you switch from Data Annotations the Fluent API.
Here's an example.
The Entity1 object is a core layer domain object:
namespace MyApp.Core.Model
{
public class Entity1
{
public short Id { get; set; }
public string ExternalCode { get; set; }
public byte Status { get; set; }
}
}
In the infrastructure layer, create an Entity1Mapping class where you'll do what you'd have done using Data Annotation, but this time, with the Fluent API instead:
using System.Data.Entity.ModelConfiguration;
namespace MyApp.Infrasrtucture.Data.Configuration
{
internal class Entity1Mapping : EntityTypeConfiguration<Core.Model.Entity1>
{
internal Entity1Mapping()
{
HasKey(g => g.Id);
Property(g => g.Id).IsRequired();
Property(g => g.ExternalCode)
.IsRequired()
.HasMaxLength(100)
.IsVariableLength()
.IsUnicode(false);
Property(g => g.Status).HasColumnName("EntityStatus").IsRequired();
}
}
}
Last thing you have to do, is adding the mapping in the modelBuilder of your context:
using System.Data.Entity;
namespace MyApp.Infrastructure.Data
{
public class MyContext : DbContext, IDbContext
{
public MyContext() : base("ConnectionStringMyContext")
{ }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<MyContext>(null);
modelBuilder.Configurations.Add(new Configuration.Entity1Mapping());
}
}
}
This is the IDBContext just in case:
public interface IDbContext
{
DbSet<T> Set<T>() where T : class;
DbEntityEntry<T> Entry<T>(T entity) where T : class;
int SaveChanges();
void Dispose();
}

Using FluentAPI is a good a solution in my opinion.
It is worth noting though that System.Component.DataAnnotations does not rely on EntityFramework - so you can use DataAnnotations in your core project and still be agnostic on your particular persistance mechanism.

Related

CRUD and Query with ServiceStack - Need to get rid of some confusion

I am a bit confused with ServiceStack 'old' and 'new' API and need some clarification and best practices, especially with Request / Response DTO's and routing. I watched some courses on Pluralsight and have the first three books listet on servicestack.net in my electronic bookshelf.
I like to 'restify' an existing application which is built using DDD patterns which means I have a high level of abstraction. The client is WPF and follows the MVVM pattern. I have 'client side service', 'server side service' and repository classes (and some aggregates too). I use NHibernate 4 (with fluent API and a code-first approach) as ORM. Only my repository classes know about the ORM. I have DTO's for all my Entity objects and in my WPF client I only work with those DTOs in the ViewModel classes. I heavily use AutoMapper to 'transfer' Entity objects to my DTO's and vice versa.
My confusion starts exactly with these DTO's and the Request / Response DTOs used in ServiceStack. Here is a very much simplified example of an Address Entity which illustrates the problem:
All my Entity Objects derive from EntityBase which contains basic properties used in all Entities:
public abstract class EntityBase : IEntity
{
public virtual Guid Id { get; protected set; }
public virtual DateTime CDate { get; set; } //creation date
public virtual string CUser { get; set; } //creation user
public virtual DateTime MDate { get; set; } //last modification date
public virtual string MUser { get; set; } //last modification user
//
// some operators and helper methods irrelevant for the question
// ....
}
public class Address : EntityBase
{
public string Street { get; private set; }
public string AdrInfo1 { get; private set; }
public string AdrInfo2 { get; private set; }
public string ZipCode { get; private set; }
public string City { get; private set; }
public string Country { get; private set; }
}
Of course there are collections and references to related objects which are ignored here as well as database mappers, naming conventions etc. The DTO I have looks like this:
public class AddressDto
{
public Guid Id { get; set; } // NHibernate GUID.comb, NO autoincrement ints!!
public DateTime CDate { get; set; }
public string CUser { get; set; }
public DateTime MDate { get; set; }
public string MUser { get; set; }
public string Street { get; private set; }
public string AdrInfo1 { get; private set; }
public string AdrInfo2 { get; private set; }
public string ZipCode { get; private set; }
public string City { get; private set; }
public string Country { get; private set; }
}
To use this with ServiceStack I need to support the following:
CRUD functionality
Filter / search functionality
So my 'Address service' should have the following methods:
GetAddresses (ALL, ById, ByZip, ByCountry, ByCity)
AddAddress (Complete AddressDTO without Id. CDate, CUser are filled automatically without user input)
UpdateAddress (Complete AddressDTO without CUser and CDate, MDate and MUser filled automatically without user input)
DeleteAddress (Just the Id)
For me it is pretty clear, that all Requests return either a single AddressDto or a List<AddressDto> as ResponseDTO except for the delete which should just return a status object.
But how to define all those RequestDTO's? Do I really have to define one DTO for EACH scenario?? In the books I only saw samples like:
[Route("/addresses", "GET")]
public class GetAddresses : IReturn<AddressesResponse> { }
[Route("/addresses/{Id}", "GET")]
public class GetAddressById : IReturn<AddressResponse>
{
public Guid Id { get; set; }
}
[Route("/addresses/{City}", "GET")]
public class GetAddressByCity : IReturn<AddressResponse>
{
public string City { get; set; }
}
// .... etc.
This is a lot of boilerplate code and remembers me a lot of old IDL compilers I used in C++ and CORBA.....
Especially for Create and Update I should be able to 'share' one DTO or even better reuse my existing DTO... For delete there is probably not much choice....
And then the filters. I have other DTOs with a lot more properties. A function approach like used in WCF, RPC etc is hell to code...
In my repositories I pass an entire DTO and use a predicate builder class which composes the LINQ where clause depending on the properties filled. This looks something like this:
List<AddressDto> addresses;
Expression<Func<Address, bool>> filter = PredicateBuilder.True<Address>();
if (!string.IsNullOrEmpty(address.Zip))
filter = filter.And(s => s.Zip == address.Zip);
// .... etc check all properties and dynamically build the filter
addresses = NhSession.Query<Address>()
.Where(filter)
.Select(a => new AddressDto
{
Id = a.Id,
CDate = a.CDate,
//.... etc
}).ToList();
Is there anything similar I could do with my RequestDTO and how should the routing be defined?
A lot of questions raised here have been covered in existing linked answers below. The Request / Response DTOs are what you use to define your Service Contract, i.e. instead of using RPC method signatures, you define your contract with messages that your Service accepts (Request DTO) and returns (Response DTO). This previous example also walks through guidelines on designing HTTP APIs with ServicesStack.
Use of well-defined DTOs have a very important role in Services:
You want to ensure all types your Services return are in DTOs since this, along with the base url of where your Services are hosted is all that's required for your Service Consumers to know in order to consume your Services. Which they can use with any of the .NET Service Clients to get an end-to-end Typed API without code-gen, tooling or any other artificial machinery.
DTOs are what defines your Services contract, keeping them isolated from any Server implementation is how your Service is able to encapsulate its capabilities (which can be of unbounded complexity) and make them available behind a remote facade. It separates what your Service provides from the complexity in how it realizes it. It defines the API for your Service and tells Service Consumers the minimum info they need to know to discover what functionality your Services provide and how to consume them (maintaining a similar role to Header files in C/C++ source code). Well-defined Service contracts decoupled from implementation, enforces interoperability ensuring that your Services don't mandate specific client implementations, ensuring they can be consumed by any HTTP Client on any platform. DTOs also define the shape and structure of your Services wire-format, ensuring they can be cleanly deserialized into native data structures, eliminating the effort in manually parsing Service Responses.
Auto Queryable Services
If you're doing a lot of data driven Services I recommend taking a look at AutoQuery which lets you define fully queryable Services without an implementation using just your Services Request DTO definition.

Is it worth to use Repository/Unit of work pattern when using Entity framework 6?

Does it make sense to create another layer over the EF6 - Repository/UnitOfWork ?
In our custom repository we can add specific queries like GetTopXXX, GetLastUpdated, etc.
Bu we can do the same in Business Logic with LINQ on DBContext.
I would highly recommend to use a repository to separate the logic that retrieves the data in your situation.
Using the Repository pattern, very briefly, you will implement all your queries such as add, edit, update defined in your interface. And the way which you interact with the database is using Entity Framework.
public interface IProductRepository
{
void Add(Product product);
}
public class ProductRepository : IProductRepository
{
private readonly DbContenxt _dbContext;
public ProductRepository(DbContext dbContext)
{
_dbContext = dbContext;
}
public void Add(Product product)
{
var product = new Product() { Name = "Test" };
_dbContext.Add(product);
_dbContext.SaveChanges();
}
}

The placement of utility classes in DDD

I'm trying to figure out where to put my utility classes in a DDD based project. The case is a follows:
I have a class called CookieAwareWebClient which is required for the core to work. Form what I've read online this seems like a class that belongs in the Infrastructure tier, however one is not supposed to refer to the Infrastructure tier from the Core tier. This means that I cannot place functionality that the Core tier depends on in the Infrastructure tier. Where then should this CookieAwareWebClient class be placed?
Without understanding exactly what you need to do, I believe that #plalx sums it up in the comments:
Establish an interface which provides the functionality that your Core tier requires
Implement this interface in CookieAwareWebClient
Use Dependency Inversion to allow the Core to use CookieAwareWebClient
Here's some code (C# in this case) with constructor injection as an example:
The interface:
namespace Core
{
public interface IBlah
{
int SomethingCoreNeeds();
}
}
The implementation by CookieAwareWebClient:
namespace Services
{
public class CookieAwareWebClient : IBlah
{
// ... rest of class
private int _somethingCookieAwareWebClientHasThatCoreNeeds;
public int SomethingCoreNeeds()
{
return _somethingCookieAwareWebClientHasThatCoreNeeds;
}
// ... rest of class
}
}
The consuming service in your Core:
namespace Core
{
public class DomainService
{
private readonly IBlah _blah;
public DomainService(IBlah blah)
{
_blah = blah;
}
public void DoSomething(DomainEntity entity)
{
entity.NeededValue = _blah.SomethingCoreNeeds();
}
}
}

Entity Framework and base type with same name

I get the following error: The type 'EfTest.Person' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject.
when running this code:
using System.Data.Entity;
namespace EfTest
{
internal class Program
{
private static void Main(string[] args)
{
using (var db = new PersonContext())
{
db.Persons.Add(new Person());
db.SaveChanges();
}
}
}
public class PersonContext : DbContext
{
public DbSet<Person> Persons { get; set; } //people ;)
}
public class Person : EfTest2.Person
{
public int PersonId { get; set; }
public string Name { get; set; }
}
}namespace EfTest2
{
public class Person
{
public int Age { get; set; }
}
}
can you help and explain why new type can not have same name as its base?
I would focus on the keyword nested in the error. I'm sure taking it out of EfTest2 namespace and keeping the namespace the same will correct this issue. Of course then you must change the base class name from Person to some thing else.
EF has quite complex multi-layered mapping and some of these layers are not directly visible outside. This is a problem of mapping objects into their entity representation in EDM. The point is that EF is not using full class names (including namespaces) but only bare class names so your Person classes are in collision and only one can be resolved.
The origin of this behavior is probably in EF 4.0 when it was used to simplify class creation for POCO models and make namespaces independent on the EDMX.
I think you cannot write the class next to the main session.
You have to separate it to another cs file.
I solved the problem by doing that. Worth a try

Can/Should a domain object be responsible for converting itself to another type?

We have a class Event (it's actually named differently, but I'm just making abstraction):
public class Event
{
public string Name { get; set; }
public string Description { get; set; }
public EventType EventType { get; set; }
}
We need to build an instance of a Message class with this object, but depending on the EventType, we use a different builder:
switch (event.EventType)
{
case EventType.First:
message = FirstMessageBuilder.Build(event);
break;
case EventType.Second:
message = SecondMessageBuilder.Build(event);
break;
}
Do you think this is acceptable, or should we take the following approach:
Make an abstract class:
public class Event
{
public string Name { get; set; }
public string Description { get; set; }
public abstract Message BuildMessage();
}
Then derive two classes: class FirstMessage and class SecondMessage and make the domain objects responsible for building the message.
I hope it isn't too abstract. The bottom line is we need to transform one class to another. A simple mapper won't do, because there are properties with XML content and such (due to a legacy application making the events). Just accept what we're trying to do here.
The real question is: can a domain object be responsible for such a transformation, or would you not recommend it? I would avoid the ugly switch statement, but add complexity somewhere else.
Whilst I agree with Thomas, you might want to look at the following design patterns to see if they help you:
Vistor Pattern
Double-Dispatch Pattern
Builder Pattern
Strictly speaking, a domain object shouldn't be responsible for anything other than representing the domain. "Changing type" is clearly a technical issue and should be done by some kind of service class, to maintain a clear separation of concerns...
In order to gain the readability of
var message = eventInstance.AsMessage();
as well following the single responsibility principle, you could define AsMessage() as an extension method of the event type.
There are few possible solutions. To use abstract factory:
public interface IMessageFactory
{
Message Create();
}
public class FirstMessageFactory : IMessageFactory
{
public Message Create()
{
//...
}
}
public class SomeService
{
private readonly IMessageFactory _factory;
public SomeService(IMessageFactory factory)
{
_factory = factory;
}
public void DoSomething()
{
var message = _factory.Create();
//...
}
}
Now you can wire IoC container to right factory for requested service.
To use Assembler which makes the transformation:
public interface IAssembler<TSource, TDestination>
{
TDestination Transform(TSource source);
}
This is quite similar to factory pattern, but if you are dependent on EventType, its possible to do it like:
public interface IAssembler<TEventType>
{
object Transform(object source);
}
I would encapsulate the logic into a separate Factory/Builder class, and use an extension method on Event to call the builder.
This would give you the best of both worlds.

Resources