I have a large set of classes implementing business logic. Most have a .Load method that uses plain old ADO.net to read values from Sql Server that I've written by hand over the years. This all predates Linq2Sql and EF.
Now I want to update my class library to use Entity Framework but I'd like to do it as painlessly as possible. I've learned EF can infer column and key names from property names in my classes, but my classes have many properties that don't correspond to column names and some properties that don't match the database's column names. I'd prefer not to have to .Ignore() each of those properties (and remember to always .Ignore() any future properties) and .HasColumnName() all the differences.
What's the easiest way to use EF with existing tables AND existing classes so I can do minimal mappings and still use a DbContext to .Find() an entity and SaveChanges() and all the other nice strongly-typed things EF supports without going through all my business classes by hand and annotating which properties to include?
For example, I'd expect to be able to db.Customers.Find(123) and have it create a Customer instance, select * from customers where CustomerID=123, and map the columns that DO exist to the properties that DO exist as best as possible and give me a ready to use Customer instance and then I can annotate any differences as needed. Is this possible or am I asking too much of EF?
Is there maybe a smarter DbContext that will make a best effort to map properties so I can leverage all my existing business classes? Maybe I should consider some other ORM?
Try this:
create a data model (.edmx) from your database.
edit the model, Adding property and procedures of your Class That You want to add to the database.
Finally, update your database from your model (.Edmx) Selecting only the tables and procedures exist That You Have changes.
You can look at those tutorials
http://msdn.microsoft.com/en-us/data/gg685494
http://msdn.microsoft.com/en-us/data/gg685489
EF4 “Code First” enables you to optionally override its default database persistence mapping rules, and configure alternative ways to map your classes to a database.
There are a few ways to enable this. One of the easiest approaches is to override the “OnModelCreating” method defined on the DbContext base class:
public class YourContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Mapping
}
}
You can still search your entities by Primary Key by using Find:
var unicorn = context.Unicorns.Find(3);
Related
I have the following Entity classes
Associate
Project
Allocation
Associate and Project are connected by an Allocation.
I have the standard structure of a spring boot application - the above entity classes, controllers, services, and repositories for each of the entities.
If I need to find/add/update/delete an Associate, I put the code in the Associate related #Repository and similarly for all the other entities.
I have a stored procedure call, that is a complex amalgamation of all the three tables (and returns columns in all thee tables), that logically doesn't come under any of the Entity classes (Its not simple like - all the Projects of an Associate, so that I can put it in Associate related classes)
So my question is - where do I put the call to the stored procedure?
Should I create a separate Entity class for the result type of the stored procedure and add its own controllers, services, repositories although I am pretty sure there is a better way of doing it.
I'd say it depends.
Having a separate repository for this the right approach if the result type and the algorithm implemented is really something separate from the original entities.
But in some cases it is really just one of the entities with some extra data in which case I'd put it in the repository of that entity.
In the first case note that nothing forces you to implement the repository using Spring Data. It is perfectly fine for such a case to have a manually implemented repository that is just normal bean with an EntityManager injected. This way it doesn't need an entity nor id type.
As Jen and others mentioned, if the procedure is returning the collection of data from one or more tables, in my project i kept this in one of the entity repository class where it is most suitable. I have also followed EntityManager approach like below in my service class
id = (Integer) entityManager.createNativeQuery("select get_next_global_id(?, ?)")
.setParameter(1, sequence)
.setParameter(2, status.toString())
.getSingleResult();
I am using Entity Framework to create a Model, I am pretty new to the Entity Framework so bear with me.
I want my database to always be the end all be all of what gets generated, so I dont wnat to make modifications to the model itself. I want to amke all modifications to the database and just hit "Update Model From Database." This has been working swimmingly!
However If I have a one to one relationship between two tables, and I have a foreign key constraint set in the database, I get a navigation property in the child table that goes back to the parent table.
So if I want to access the parent from the child I can do child.parent.fieldName
That sounds great in theory but my issue arises when I need to serialize the object for JSON created by the entity Framework. I always get an error because it tries to serialize the parent object along with the child object. which usually has an invalid state at this point so.. A) it cant be serialized and B) I wouldn't want all that extra info anyway.
Am I misconfiguring the database in some way? is there a way to have the database specify that I only want Parent.Child Navigation properties in the model? and not Child.Parent?
Am I misconfiguring the database in some way? is there a way to have the database specify that I only want Parent.Child Navigation properties in the model? and not Child.Parent?
No. Database knows nothing about your intention to use some tool on top of it. If you don't want the navigation property you must change it in EDMX by deleting it but sometimes you want the property but you also want a serialization. In such case you must either modify strategy used to generate your classes (if you are not using T4 templates it will be quite hard) to use some special attributes dependent on used serialization API to mark some properties as not serialized.
The correct approach is not serializing entities but creating special data transfer objects filled from entities which will contain only properties/data you are going to serialize so you will not get into this problem.
I'm using CodeFirst of EF with a well defined Database.
My Database has a table named 'Centros' (Portuguese word) and I manage to find that EF tries to pluralize my entities to get a 'Centroes' witch is wrong in this case.
If I remove the pluralization modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); i manage to get it to work BUT I have to rename my table to 'Centro' (to match my entity name).
In Portuguese 'Centro' is singular, 'Centros' is plural.
I don't want to rename my table names so how can I specify the matching table name for my entity after a remove the pluralization convention?
I annotate all my classes, regardless of whether the framework can do it for me through some smart reflection routines. E.g.
[Table("Order")]
public class Order
{
}
We can touch type, it's cleaner and it's less likely to fall over in some unexpected event.
Or you can do one at a time like this in Fluent API:
modelBuilder.Entity().ToTable("ContactInfo");
ModelBuilder is now System.Data.Entity.DbModelBuilder.
I have used both the EF code first and model first apporaches. In my case the model first approach has overall been better for my use. The only thing I miss from code first is that it would auto generate the mappings, and then use those mappings to create a database. Is their any way that I can get model first to do this same thing, namely create the mappings automatically when it instantializes the database.
The EDMX designer should handle this already. When you first generate a database from your model, EF will create the appropriate mappings for you.
I have a LINQ-to-SQL data context in which two tables exist with different names but identical structures. One table (called CallRecords) holds live/current data, and the other (CallRecordsArchive) holds older records - but with the same field names as the live one.
With the basic mapping LINQ to SQL creates two classes CallRecord and CallRecordsArchive - but since they are the same I'd like to avoid this if possible? That way I don't have to write two queries for each instance?
I did consider creating a JOIN view but with millions of rows in both tables it would be a performance nightmare.
The way I've dealt with this is to create an interface for the common aspects of both tables and have both of the generated classes from your data context implement that interface through the use of the a partial class definition. This way when you want to deal with the type as a single concept you can always refer to it as the interface.
try to use inherit for this issue
check this link for more details.
one more
I hope it is help you.