I am making an library which will be used to talk with database using Entity framework. For different workflows I need different tables from database. So I decided to have separate models for separate workflows. But for some workflows one entity is used in multiple models. Now for one model I have modified my entity class (changed some getters/setters and added custom functions). But when I create new model for different workflow then model will generate entity with default names. I have to edit it again and code will be duplicated. Both are in different namespaces (one is Model1Namespace, second is Model2Namespace).
So what I exactly need is that if entity is used in different classes a single code is used (no duplicate code). What are the best practices? Do EF provide us something or we need to implement it ourself?
Example:
Database tables: TableA, TableB, TableC, TableD
Models: Model1 -> TableA, TableB
Model2 -> TableA, TableC,
Model3 -> TableC, TableD
Edit:
I have a database containing 4 tables (TableA, TableB, TableC, TableD). I create a Entity data model of the database which contains TableA and TableB. In entity designer view I modified names of properties of TableA Entity so that they are readable. Now I create another model which contains TableA and TableC. Now here I have to rename all properties of TableA again. Now this is repeat work. Now if I add some custom action to my Entity for Model1 then I have to write (copy) them to new Model2 Entity as well. I need to avoid this. As I really don't know how many models I will create. And if I have to do this stuff again and again then it will take lot of time.
Related
I have created a view "Supplier" that shows columns from a table "T_ADDRESS". The view is declared as (I know, the '*' is a no-go in views)
create View Supplier as
select * from T_ADRESSEN where IsSupplier = 1
In EF, I want to use the view as it is more readable than the ugly "T_ADRESSEN". So far so easy.
Now comes the tricky part (for me). The table T_ADDRESS has a self referencing foreign key "MainAddressId" which points to T_ADDRESS.
Creating a DB-first (or CodeFirst from DB) will create the FK relationship for the table T_ADDRESS (and the navigational properties), but not for the view 'Supplier'. Of course not: EF does not know anything about the FK relationship (although the view exposes the same columns).
Now I tried to use the 'ForeignKey' and 'InverseProperty' attributes in my code first model on the Supplier-class but this gives me an ModelValidationException. Also clear: There is no such FK-relationship.
How can I tell EF to treat a field just like a foreign key although the constraint does not exist?
What I am trying to do is to have 'Suppliers' in my EF model (as a subset of T_ADDRESS). If there is another way to do it, I would be happy to receive a hint.
You can't define ForeignKey and InverseProperty on a view. In your case, you need to use that ugly T_ADRESSEN table and use [AutoMapper][1] to map it the to the DTO class. In your case, T_ADRESSEN is the context table and Supplier is your DTO class.
with AutoMapper you can do something like this:
var ugly = context.T_ADRESSEN.Where(e=>e.IsSupplier ==1);
var suppliers = mapper.Map<IEnumerable<Supplier>>(ugly);
where mapper is IMapper interface defined in AutoMapper.
Sometime one should figure out that the DTO mapping technique as a replacement to the traditional database view.
I'm rather new to software development and I am very confused as what classes in the model should represent, i will elaborate a scenario and i will ask a couple questions at the end. I'm using VS 2013 with MVC.
I have 3 tables,
tblStudent (*StudentID, StudentName, StudentLastName, StudentDateOfBirth)
tblModule (*ModuleID, ModuleName, ModuleDescription)
tblStudentModules (*StudentID, *ModuleID) - table created to break many to many relationships
And i want to execute this query using a stored procedure in the database:
SELECT A.StudentID
,A.StudentName]
,A.StudentLastName
,B.ModuleName
FROM tblStudent A, tblModule B, tblStudentModules C
Where A.StudentID = C.StudentID
And B.ModuleID = C.ModuleID
Now, my query uses 3 tables, and the result is a combination of different attributes of the tables i have, so should my model classes represent individual objects (i.e Student, modules ) or should they represent the result set of the Query that i want to execute (a class with StudentID, StudentName ,StudentLastName, ModuleName) so I can map the result of the stored procedure to a single model class?
Models are the business layer when considering MVC applications. It will be created based on database structure. Always create models for the tables of your database.
That is, you should need to create models for tblStudent , tblModule and tblStudentModules .
ViewModel is one of the unspoken layer in the Asp.Net MVC application. It fits between Model and View and act as a data container for View. ViewModel is View specific data. It will be created based on the View. So, you need to create viewmodels based on every view. These viewmodels may or may not contain variables of the original models.
That is, you need to create a viewmodel for the stored procedure you are writing which contains StudentID, StudentName, StudentLastName and ModuleName. That is, what all things we need to display in a view page are the variables of the viewmodel.
View is going to be a strongly typed view of type ViewModel.
Model and ViewModel should be independent of each other. Controller
will create and initialises ViewModel object based on one or more
Model object.
Personal opinion - but a class in a model as described above should represent a 'thing', be it a Student, a Module, or a Relationship between the two.
If you were to use Entity Framework for example to interact with the database from code then this is how the database would be represented, a collection of three classes, one for each of the tables you have described.
This is a very complex subject that can't have a quick answer however the cut down version is:
Don't confuse the database model with the object model, while there are many point of similarity they are not the same thing.
An Object is a Entity that contains naturally grouped items and functions
Where as a Table is normalised representation of data
To use your example you have Students and Modules that are primary entities that uses a 3rd table to maintain a relationship
On the object model you would have a Student class, and a Module class
the Student class would have a collection of modules inside it. so the student will manage its own relationships with modules and each module may contain a collection of student allowing it to maintain its relationship as well.
However a Student is a Type of Person so you might define a Person class and then have student Inherit from this class and expand its functionality to include student behaviour, now in this situation a person would probably not have any meaning unless filter through a child class such as student or teacher.
in the database this is hard to maintain as you can't have a person table that doesn't exist
This is where the idea of MVC and MVVM comes in as this encourages you to create a layered system so you have your bottom layer that manages the database object relationship and your top layer that handles your User object interaction
Here's my question. I have 2 models (Person, Event) and with EF and modelbuilder I generate a booking table (with IdPerson and IdEvent as properties).
So in my DB it's correct, I have 3 tables (Person, Event and Booking) with many to many relationship. But I have only 2 models in Visual Studio (Booking doesn't exist because of the self-generated table).
With my Controller I want to write an action for the Person to suscribe to an event and I have to write on my table Booking on the DB but it doesn't exist as a model so I can't do that .
How should I proceede?
Should I create a Booking model and delete my modelbuilder?
When you are using ORMs like EF, you can sit back and let the ORM manage these middle tables.
You can use
person.Events.Add(event)
or
event.People.Add(event)
and EF handles all and inserts a row with personId and eventId in that table.
Here you can find a complete sample:
http://blogs.msdn.com/b/wriju/archive/2011/05/14/code-first-ef-4-1-building-many-to-many-relationship.aspx
I assume this is a model first approach.
The reason for having only 2 objects is that, by default, EF does not create objects for joint tables. What it does create is Navigation Property (Entity Framework - Navigation Property Basics). In one-to-many scenario, a navigation property inside a parent object contains a collection of entities in a foreign / child table. In many-to-many scenario, navigation properties of each entities will simply contain collections of its other entities.
I have a class, suppose it's called EntityModel, and I want to make three different tables with the same columns, as defined in EntityModel. Let's call the tables tbPast, tbPresent and tbFuture. I want also to access them separetely in the Entity DbContext:
using (var db = new MyContext())
{
var element = db.Past.Find(id);
db.Past.Remove(element);
db.Present.Add(element);
db.SaveChanges();
}
The main purpose of having three tables is performance: the table will have millions of rows, and the most important is the Present, with dozens of rows. Most queries will be made in the Present table.
What is the best way to do this? Implementing three models with the same properties doesn't seem right for me.
I'm using Entity Framework, with the Code First approach, along with ASP.NET MVC 3.
You can't use the same model to generate separate tables w/ EF code-first. If you need to have some sort of grouping, use a Discriminator field and assing it any of the values: Past Present Future.
Edit:
Similar effect can be achieved through table-per-concrete type inheritance. Thus each type will have it's own table and can share most (if not all) of the fields.
I am stuck here.
Is it possible to map data from 2 different tables to 1 entity in Entity Framework 4.
I have a bunch of employees in one table, and in the other I have som project information.
I would like to combine these 2 tables in one Entity, and keep the tracking features etc., is that possible?
I do not want to use a function import, but do it solely through the Entity Model.
Can anyone help - when I try to do it, i get the following error all the time:
Error 3024: Problem in mapping fragments starting at line 2354:Must specify mapping for all key properties (MyProjectTable.PSInitials, MyProjectTable.ProjectID) of the EntitySet MyProjectTable.
Both key are mapped to their respective tables.
The new Entity are made with MyProjectTable as the basetable.
The relation between the 2 tables is a 1-*
Hope you can help.
/Christian
You cannot map two tables with a one-to-many relationship to one entity. If you don't want projecting the results into one object in code, consider creating a view and mapping it instead.
According to http://msdn.microsoft.com/en-us/library/bb896233.aspx
You should only map an entity type to
multiple tables if the following
conditions are true:
The tables to which you are mapping share a common key.
The entity type that is being mapped has entries in each
underlying table. In other words,
the entity type represents data
that has a one-to-one correspondence between the two
tables; the entity type represents an
inner join of the two tables.
The reasons for doing this are quite straightforward - for example, a table of data points that all have one of five 'types'. Obviously the 'type' will be a separate table for the sake of normalisation, but from an application point of view (working with the data) it makes more sense to have all properties in a single entity.
So we can't do this with Entity Framework - a supposed Object-Relational-Mapper. What, then, is the point of using such a framework?