What is model in EF Core context class? [duplicate] - entity-framework

This question already has answers here:
What is the difference between a "Model" and a "Context" in Entity Framework jargon?
(3 answers)
Closed 3 years ago.
The class DbContext has a virtual method OnModelCreating that one should override when wanting to change the model it creates.
Throughout the tutorials i came across the term Model many times, without knowing what it really is?
Is it the same Model as in EDM? or part of it?

So, your Model is your POCO class (or DTO). You will see many different names for the same thing.
But it's a Model example:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
EDM files are responsible for the mapping your Model to the database.
Remember that 3 differents way to work with EF. You have Code First, Database First and Designer First. The concept of EDM can get a little difference between them.
My answer is not complete about the theme, it's just a 'mindset' for you.

Related

Why Navigation Properties are virtual by default in EF

I have following POCO class being used in EF 6.x.
My question: Why is the navigation property of 'Posts' under 'Blog' entity declared as virtual?
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Tags { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
If you define your navigation property virtual, Entity Framework will at runtime create a new class (dynamic proxy) derived from your class and uses it instead of your original class. This new dynamically created class contains logic to load the navigation property when accessed for the first time. This is referred to as "lazy loading". It enables Entity Framework to avoid loading an entire tree of dependent objects which are not needed from the database.
In some circumstances, it is best to use "Eager Loading" instead, especially if you know that you will be interacting with related objects at some point.
Julie Lerman really is the authority on all things Entity Framework, and she explains this process very well in her MSDN Article Demystifying Entity Framework Strategies: Loading Related Data
Eager loading with Include is useful for scenarios where you know in advance that you want the related data for all of the core data being queried. But remember the two potential downsides. If you have too many Includes or navigation paths, the Entity Framework may generate a poorly performing query. And you should be careful about returning more related data than necessary thanks to the ease of coding with Include.
Lazy loading very conveniently retrieves related data behind the scenes for you in response to code that simply makes mention of that related data. It, too, makes coding simpler, but you should be conscientious about how much interaction it’s causing with the database. You may cause 40 trips to the database when only one or two were necessary.
If you are developing a Web Application where every communication with the server is a new context anyway, Lazy Loading will just create unnecessary overhead to maintain the dynamic class for related objects that will never be loaded. Many people will disable lazy loading in these scenarios. Ultimately, it's still best to evaluate your SQL queries which EF has built and determine which options will perform best for the scenario you are developing under.

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.

Entity Framework, Code First and One-to-Many relationship across multiple contexts

I am using VS 2010 and Entity Framework code first (version 6). I have two entities each in its own context and I want to create a one-to-many relationship between them.
Context 1 has the following entity:
public class MyTrust
{
public int MyTrustID { get; set; }
public string MyTrustName { get; set; }
}
and Context 2 has the following entity:
public class MyLocation
{
public int MyLocationID { get; set; }
public int MyTrustID { get; set; }
public virtual MyTrust MyTrust { get; set; }
}
with the following Fluent API
modelBuilder.Entity<MyLocation>()
.HasRequired(m => m.MyTrust);
The migration file for Context 2 contains the correct keys but also creates a new table for MyTrust which already exists in the other context.
I know that I can edit the migration file but that is not a solution.
My question is, how to I stop the creation of the second MyTrust table.
UPDATE
There was a major flaw above in that I pasted the wrong code into Context 2. Now corrected. Apologies.
You are working with so-called bounded contexts. The benefit of such contexts and how to work with them is explained in this blog by Julie Lerman.
The problem you experience, none of the contexts can be used in migrations, is addressed in this part:
If you’re doing new development and you want to let Code First create or migrate your database based on your classes, you’ll need to create an “uber-model” using a DbContext that includes all of the classes and relationships needed to build a complete model that represents the database.
Note that you can share the MyTrust type between all contexts, if you observe these rules (from Lerman & Miller's book DbContext, p 233):
An entity can only be attached to one context at a time. This architecture works
best with short-lived contexts where the instance to be shared will be completely
disassociated from one context before it is attached to another.
Entities that are attached to different contexts cannot be attached to one another.
UPDATE
In EF6 you can use multiple contexts for one migration path. See this walkthrough.

Entity Framework with existing database

I'm looking to implement entity framework version 4.3.1 in my existing project which don't follow this EF.The database is already developed and is currently used applying ado.net.In this case how do I start with to work on EF, is it Database First,Code first.
Even when a database already exists I still use the Code First approach, mapping the tables using annotations, because the domain is way more organized than on the EDMX file. If there are many tables the visual EDMX can become really useless since the design will be overcrowded with data and connections all over the place.
In two steps you can begin with this approach:
1) Create a domain model class, Customer for example, and map it to your table using data annotations:
[Table("tbl_cust")]
public class Customer
{
[Key]
[Column("cust_id")]
public int CustomerId { get; set; }
[Column("cust_name")]
public string Name { get; set; }
// Add other properties below
}
2) Create a context class deriving from DbContext and set DbSet<T> properties for each model, we have only one in our case so:
public class MyApplicationContext: DbContext
{
public MyApplicationContext() : base("name=ConnectionStringName") { }
public DbSet<Customer> Customers { get; set; }
}
Now anywhere in your code can instantiate the derived DbContext class and make queries using Linq:
var _db = new MyApplicationContext();
var customer = _db.Customers.Where(c => c.CustomerId == 37).FirstOrDefault();
Don't forget to add a reference to EntityFramework assembly using NuGet.
Good Luck.
Since your database already exists the obvious choice is Database first. If the database is designed with common sense it (mostly) works great.
I think the question is if you want to use the EF Designer to visualize your database or not. Since you are looking at EF 4.3.1 (in fact you should be looking at EF5 not 4.3.1 - EF5 is the latest version) I assume you don't care about the designer. In this case you could use EF Power Tools to reverse engineer your database. This will create a set of classes that will match your database. Note that since the database has already been created EF will not be able to detect changes in your classes (as opposed to databases created by Code First when additional information is stored in the database and EF is able to tell whether the model has changed). Make sure to read this blog post - it contains a lot of details you may find helpful to make the decision.
If you care about being able to see your model in the designer you can just use VS to reverse engineer DB. If you use VS2012 you will by default get EF5 and DBContext. The difference from using Code First will be that instead of building the model EF needs based on your classes the model is saved in the the edmx file that is part of your project (and used to generate code for you)

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.