Entity Not Mapped - Entity Model Framework - c#

I'm having a lot of difficulty with the Entity Model Framework.
I'm just learning how to use this, so please bear with me.
This is the exception, along with the line of code that it gets thrown on:
This is what the model looks like, along with the model that it inherits from
This is what the mapping details looks like: (Top of if statement was cut off)
Here's what AccountContext looks like
If I didn't provide enough information then please let me know
How do I map the "User" Entity?

You have a class hierarchy there and there are three different strategies for inheritance mapping: TPH, TPT and TPC.
As far as I understand in all three strategies you need to include the Base class into you DbContext:
public class AccountContext : DbContext
{
public DbSet<BaseModel> BaseModels { get; set; }
}
This leads automatically to TPH mapping. For the other two strategies you need additional mappings either by data annotations or in Fluent API.
Edit
To query for your derived classes (like User) you can work with the OfType method, for instance:
UserDb.BaseModels.OfType<User>().ToList()
This would return all entities of type User into a list.

Related

DDD aggregate and entity framework. Which way is preferable?

I am little bit confused about the problem. I have an entity Product that is represented in the database. It looks like POCO. Here is example (I use attributes instead of fluent api for simplicity).
public class Product
{
[Key]
public int Id { get; set; }
//other properties that have mapping to db
}
But now I want to avoid AnemicDomainModel anti-pattern
So I am going to fill the Product model with methods and properties, that do not have mapping to db, so I should use [Ignore].
public class Product
{
[Key]
public int Id { get; set; }
[Ignore]
public object FooProperty { get; set; }
//other properties that have mapping to db
//other properties and methods that do not have mapping to db
}
I think such a way spoils my model. In this article I've found acceptable workaround. Its idea is to separate Product (domain model) and ProductState (state of product that is stored in the database). So Product is wrapper for ProductState.
I really want to know the views of other developers. Thanks a lot for your answers.
I understood that my real question sounds something like that: "Should I separate Data model and domain model? Can I change EF entities from Anemic to Rich?"
To ensure persistence ignorance of your entities, I've found EF Fluent Mapping to be better than Data Annotations. The mappings are declared in an external file, thus normally your entity doesn't have to change if something in the persistence layer changes. However, there are still some things you can't map with EF.
Vaughn's "backing state object" solution you linked to is nice, but it is an extra layer of indirection which adds a fair amount of complexity to your application. It's a matter of personal taste, but I would use it only in cases when you absolutely need stuff in your entities that cannot be mapped directly because of EF shortcomings. It also plays well with an Event Sourcing approach.
The beauty of the Entity Framework is that it allows you to map your database tables to your domain model using mappings which can be defined using the Fluent API, therefore there is no need to have separate data entities. This is in comparison to its predecessor Linq To SQL where you'd map each table to an individual data entity.
Take the following example, for the paradigm of a Student and Course - a student can take many courses, and a course can have many students, therefore a many-to-many relationship in your database design. This would consist of three tables: Student, Course, StudentToCourse.
The EF will allow you to use Fluent API mappings to create the many collections on either side of the relationship without having the intermediate table (StudentToCourse) defined in your model (StudentToCourse has no existence in a DOMAIN MODEL), you would only need two classes in your domain, Student and Course. Whereas in LinqToSQL you'd have to define all three in your model as data entities and then create mappings between your data entities and domain model resulting in lots of plumbing work open to bugs.
The argument of the anaemic vs rich domain model should have little effect on your mapping between your model and database tables, but focuses on where you place the behaviour - in either the domain model or the service layer.

EntityFramework 5 Validation

I'm looking for some advice. I'm working with EF 5 and I have a generic repository which handles all of the CRUD transactions with the database. This works fine, But i want to add a "Last Gap" safeguard to ensure that the entity is valid before the Data Access Layer attempts changes in the database.
Right before I do something like this :-
DataLayer.Create<TEntity>(entity);
I want to Validate the entity and throw an exception if the validation fails.
What would you guys use as the preferred method?
Using Data Annotations
You can use data annotations directly in your entity. With data annotations, EF will validate the property for you and if it is not valid, an exception will be thrown.
For example, if you want Name to be required, you can do something like:
public class Person
{
[Required]
public string Name { get; set; }
// other members
}
Aside from validation, EF will also set the corresponding column to be not null instead of the default null for strings.
Using the Fluent API
If you don't want to litter your entities with data annotations, you can use the fluent API instead. Following is the equivalent of the above code:
public class MyContext : DbContext
{
public DbSet<Person> People { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Entity<Person>().Property(p => p.Name).IsRequired();
}
// other members
}
My answer applies to EF Code First and may not apply for other workflows.
Sometimes you have to go to the database to check whether inserting or updating an entity keeps the repository in a valid state - such as when you need to ensure the natural key is unique. That isn't currently handled by a data annotation or the Fluent API, although it has been discussed. See unique constraints in entity framework And this work item.
In the meantime, when you have to go to the database then DbContext will be involved somewhere, and DbContext has an Overridable method called ValidateEntity. See this article: Entity Framework Validation.
I put the code I use in another answer here
And more about how I've structured the validation in MVC here.
I wouldn't do validation at the DAL, but if you do, you might be interested in Validation with the Data Annotation Validators

Validation in data first approch

I am implementing a project using mvc 4 and entity framework.
where i used data first approach. and i am implementing a partial class for my models for various business logic.
my question is how can i set validation rule on my properties. shown in below.
[Required]
public string FirstName { get; set; }
if i manually added this code "[Required]" on a property (entity framework generate models).
and then if i need to change model for database changes. then all my validation rule is gone
how can i over come this problem, without using code first approach.
As you've found out you should never edit the generated files since changes are lost when you regenerate them.
A better architecture than to use the entities as models for your views is to insert a separate View Model between the view and the entity. The view model should correspond closely to the needs of the view and often retrieves data from several underlying entities.
The attributes then goes on the view model properties instead of on the entities.
View models also remedies the risk of mass assignment vulnerabilities in your application, which are particularly dangerous if you are using lazy loading in your entities.
Another way around this (using CodeFirst) is to use a Fluent Validation. The CustomerValidator will always point at the regenerated Customer class (unless you change the Customer class name obviously)
using FluentValidation;
public class CustomerValidator : AbstractValidator<Customer> {
public CustomerValidator {
RuleFor(customer => customer.Surname).NotNull();
}
}

Should I refer to Entity Object class always as DAL or I can use its classes?

Let's say I have 'Customer' table in SQL DB and I'm using Entity Framework.
Now, for instance, in Controller or ViewModel I retrieve the customer by var customer = Page.Current.Customer when it's code is:
public class Page
{
...
// Customer is EntityObject that created by Entity Framework
public Customer Customer
{
get
{
return (new ContextEntity()).Customers.First();
}
}
}
My question:
Should I refer to Entity Object class(Customer) as DAL and create CustomerWrapper or I can use it in other code of my application?
I mean, is it correct that Page.Current.Customer will return Customer Entity or I should use Customer Entity as DAL and Page.Current.Customer should return custom Customer, some kind of CustomWrapper?
In one hand if will decided to change Customer table name to site_Customer(in SQL DB) I'll refresh the EntityModel and will only change the code in the Page class to
public class Page
{
...
// Customer is EntityObject that created by Entity Framework
public Customer Customer
{
get
{
return (new ContextEntity()).site_Customers.First();
}
}
}
But in the other hand I'll have Customer Entity + WrapperCustomer
What is better?
All class in an EDMX file are partial classes. This means that you can extend these classes by creating a new Class file.
For example...
public partial class Customer
{
// Here are the methods, properties, relationships created by EDMX Wizard.
}
In another area of your project, I usually put it in the same location as the EDMX, you can add a new Class file that has the same signature.
public partial class Customer
{
// Here are the methods, properties, etc. created by you.
}
When the project is compiled these two classes will become one class in the compiled code. Now, when you change your EDMX, yes it should map correctly, but this is not always the case as EF has be known to be very buggy (suppose to be fixed with EF 4.1 in MVC 3), you can simply change the class name to match whatever it is in the EDMX and "Voila!" you have transferred all custom added code for the class to the new entity object. This is essentially your "class wrapper".
That all depends on the level of abstraction you want to use in your application and needs of presentation layer. Both approaches are possible.
Your code is probably already tightly coupled to Entity Framework (EntityObject is EF type) and it is also not very well testable (Page.Current is probably static) so discussion about some more advanced architecture approaches and separation of concerns is not needed.
Few observations from your code:
Context is Disposable!!!
Renaming anything in your database should not modify your class names. That is the responsibility of EF mapping (EDMX) to correctly map entities to new database names.
If you want to use WCF, then you will probably need to create clear POCOs to avoid a lot of issues.
If you want your controllers/viewmodels/pages/whatever to be unit testable, then you will need to abstract your EntityContext in repository interfaces+classes (see repository pattern).
If you just want to make a quick and simple non-testable application, then you don't need to bother about it. Don't forget to dispose the data context at the end of each request.

Entity Framework Decorator Pattern

In my line of business we have Products. These products can be modified by a user by adding Modifications to them. Modifications can do things such as alter the price and alter properties of the Product. This, to me, seems to fit the Decorator pattern perfectly.
Now, envision a database in which Products exist in one table and Modifications exist in another table and the database is hooked up to my app through the Entity Framework. How would I go about getting the Product objects and the Modification objects to implement the same interface so that I could use them interchangeably?
For instance, the kind of things I would like to be able to do:
Given a Modification object, call .GetNumThings(), which would then return the number of things in the original object, plus or minus the number of things added by the modification.
This question may be stemming from a pretty serious lack of exposure to the nitty-gritty of EF (all of my experience so far has been pretty straight-forward LOB Silverlight apps), and if that's the case, please feel free to tell me to RTFM.
Thanks in advance!
Edit:
It would also be nice if, given a third table, linking a Products to Modifications (one-to-many) it could reconstruct the decorated object (I realize that this is likely way out of bound for the EF to do automatically). How would you recommend going about this, and where would that code reside? Would it be part of the EF classes or would every entity I received from the DB need to be passed through some sort of "builder" to construct a decorated object from a Product and its list of Modifications?
I am not entirely sure if I understood your question correctly, but here goes: You can create partial classes to those defined in your EF model. You could define a common interface and use the partial classes to implement that interface.
For example:
public interface IProduct{
public int GetNumThings();
}
public partial class Product : IProduct{
public int GetNumThings()
{
...
}
}
public partial class Modification: IProduct{
public int GetNumThings()
{
...
}
}

Categories