Entitfy Framework DbContext and xxxEntities? - entity-framework

I have a SQL server db ( with tables etc) and ive installed ef6 in order to use async stuff ( p.s. im new to ef).
So I added this :
played with the wizard and created a valid edmx files.
My db name is DUMP so it added Dumpentities suffix :'
so now i can do :
de = new DumpEntities1();
var data=de.AgeGroups.ToList()
But why don't I Have DbContext ? like I see in many places ?
Is xxxEntityes is a replacement for DbContext ?
cause it seems i can do all actions with xxEntites ...
edit
Ive searched "dbcontext" in my solution and apprently i do have it :
So what is going on here?
does using xxxEntiyies is the new way ?( and not doing xxxContext = new xxxContext()...even if I wanted - I dont have it...)

You should not use DbContext directly (that will not make sense) in Entity Framework. Instead you use your own custom context - class inherited from DbContext which holds sets specific to your application. When you use database first approach this custom entity class will be generated based on edmx file data, which in his turn will be generated based on database schema.
Regarding to naming... its not obvious but custom context which will be generated, will have same name as connection string name when you are creating edmx file:
Actually this will be default name for Entity Container of your conceptual entity model. If you will open edmx file in designer and take a look on its properties, you will see:
If you will change this name, context will be re-generated with name you have provided.

Related

DTO/POCO with Entity Framework

I'm using EF5 Model First. I don't really understand what are the auto-generated classes from the EDM. According to some documentation this classes are POCOs but why are they used in the context ?
Assuming I have a Student entity, then I get a Student POCO class and a DbSet StudentSet property in my context.
Will this next instructions put a POCO in my database ?
MyContext.StudentSet.Add(johndoe);
MyContext.SaveChanges();
So EF uses POCO to transfer data ? Actually I miss the step when POCO exchange data with entities or DTO and when the entities put data in the database.
The generated classes from the EDM is the ORM / Persistence classes. You use that classes to query / make changes from / to database. You need to translate any DTO object to POCO object when about making changes to database.
ORM is about mapping object to data in database, instead of dealing with insert into syntax to insert record to database in the application, you use StudentSet.Add to add a new data. The johndoe information will be translated into sql syntax, EF will map each property to each column when translating it into query.
The Add method will store the johndoe information as Added in the memory but it will not be executed right away to the database. If you have another Add method, it will be marked as Added too. The moment you call SaveChanges, all the changes will be saved into database by sending a generated query.
The mapping between DTO and EF entity happens before you add the johndoe. You might have another DTO class that is used in the UI. You need to map it manually or using mapper library to create a POCO object from a DTO object. For example:
// studentDto as parameter
var johndoe = new Student
{
Name = studentDto.StudentName,
Age = studentDto.StudentAge
};
MyContext.StudentSet.Add(johndoe);
// studentDto might have another information as well
var johndoeSubject = new Subject
{
Name = studentDto.SubjectName,
Years = studentDto.SubjectYears
};
MyContext.SubjectSet.Add(johndoeSubject);
MyContext.SaveChanges();

add my own property to EF designer

I using vs2010 and the built-in EF designer against SQL server Compact 4.0 local database that in my project. ( design-first)
I tried to add (through the designer) to one of the entities a new property that doesn't exist in the DB (nor planed to) by: add-new scalar property.... , but when i was tring to validate it, i got an error:
property "x" is not map
my question:
can i add my own properties to the schema through the designer. and that properties won't be exist in the underline DB.(I thought i could)?
if I can, how?
You can add non db fields to your entity by creating a partial class of that entity with the required properties. These won't be used for the ORM.
public partial class MyEntity {
public string StringStatusCode { get;set;}
}

Issues with POCO Entities

I am using POCO entities in my application.
So i have three files:
DBModel1.edmx
DBModel1.Context.tt
DBModel1.tt
Under DBModel1.tt, I have all POCO Entities.
Now my DB is copied to a new Server, wherein 1 new table has been Added to the database.
So I have to add one more POCO entity for new table.
Since now it's a complete new DB, I would have to create a new EDMX and tt files.
Is there anyway :
to make context.tt file point to new EDMX
to add new POCO Entities in existing tt file
Any help would be appreciated. Thanks.
To point .tt file to another EDMX file you just need to open the file and change its declared inputFile filed to another path.

Entity framework: Database first/Code first hybrid

I am trying to create a custom Entity Framework (4.2) entity that would be mapped to my database like it would be done in a Code first approach.
The issue is that my entity framework data model is using Database first.
How can I add my custom entity to entity framework's context?
If by the Database first you mean that you already have EDMX created from exiting database you simply cannot use code first. You must create table and update model (EDMX) from the database to include it in EDMX.
Edit based on comment:
I want to create a BriefUser entity that would basically be a lighter
version of User but it would have properties retrieved from User's
foreign keys.
Well this is possible. You can either create BriefUser as common class and use projection in query.
var breifUser = (from x in context.Users
where ...
select new BriefUser
{
// Fill BreifUser's properties here
}).FirstOrDefault();
You can even refactor former code to reusable extension method:
public static IQueryable<BriefUser> ProjectUser(this IQueryable<User> query)
{
return query.Select(x => new BreifUser()
{ // Fill BreifUser's properties here });
}
and use it like:
var briefUser = context.Users.ProjectUser().FirstOrDefault(...);
It is also possible to define your new class as "entity view". The first problem is that each table can be mapped to only one entity (except some advanced concepts like inheritance or splitting) so you cannot define your BriefUser as a new entity type because mapping both User and BriefUser to UserTbl would violate this rule. You must use special construct called QueryView.
QueryView is view in mapping level. It allows you to create new mapped type which is projection of existing mapped entities defined directly in EDMX's MSL part. The projection is defined as custom Entity SQL query. The problem is that QueryView has limitations:
It doesn't offer all Entity SQL features - for example it doesn't support aggregations (which I consider as really missing feature). Without aggregations you for example cannot create a new type which will contain property counting some related entities.
It is not supported in designer. You must edit your EDMX as XML to define QueryView and you must write Entity SQL query yourselves.
Resulting type is a "view" and it is read-only.
I want to keep the EDMX file, but also be able to add an entity
(BriefUser) to EF's context.
This is not possible. Your BreifUser is only projection / view and EF is not able to track changes back to originating tables so you cannot add BreifUser to context and persist it. In case of QueryView you can achieve it if you define custom stored procedures which will no how to decompose BreifUser and modify all related tables. These stored procedures must be imported to the EDMX and mapped to data modification operations of the view entity. Btw. same will happen if you map your entity to the database view because EF takes all views as read-only.

Changing the Name of the Connection String that Entity Framework Uses

How do you change the name of the connection string that Entity Framework models are bound to by default?
Let's say I create an Entity Framework data model named "Model1.edmx" by pointing it to a databased named "MyDb" and picking some objects to map using the Visual Studio add new item wizard. The EF model is in a class library project, so when the wizard completed, it automatically added a connection string named "MyDbEntities" to the App.Config file for the project. My model references this connection string by default.
I know I can pass in a connection string to a constructor for my model's object context, but how can I change the name of the default connection string?
I'm using VS 2010 Beta 2.
The default connection string name is simply the same as the Entity Container Name of your model.
So if you open up your model, click on a blank area, then go to the Properties window, you can look for the Entity Container Name and change it.
Note that the Entity Container Name is also used for other things. E.g., it's the class name of your ObjectContext subtype, and it's used when creating EntityKeys.