Change tables generated by Entity Framework and Code First - entity-framework

I know that you can change T4 templates used to generate the classes using Entity Framework 5.0 if you are using Model First. How would you change the template used to generate the tables when you use code first?

When using Code First there are no templates to generate tables. To set table names you can use TableAttribute or configure the table for the given entity with ToTable method in your OnModelCreating override.

Related

Entitfy Framework DbContext and xxxEntities?

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.

How should I deal with an EF code first model where no entities have keys?

I have used the Entity Data Model Wizard to generate an EF data model (an edmx with POCO's) based on the Object Catalogue Views in SQL Server, i.e. sys.objects, sys.tables, sys.columns, etc. When I try to access any data through my DbContext's DbSet properties, EF throws a ModelValidationException, complaining that entities don't have keys defined.
I can easily modify the T4 template that generates the entity POCOs to include a dummy property marked with the [Key] attribute, but this seems a bit klunky, as now my entity classes have a 'phantom' property that doesn't belong to them. Choosing a name for the key column is also an issue, but I could do something like generate a GUID for a unique key column name for ever class.
But, isn't there a better, neater way of telling EF I don't need key columns, as this model is strictly read only?
ADDENDUM: If I use the Entity Framework Power Tools - Reverse Engineer Code First tool, it creates a mapping class (derived from EntityTypeConfiguration) for each entity, and where the entity has no define key, it defines one using all the fields in the entity.

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.

Entity Framework & SQL Compact Edition - how do I get ntext?

The answer to my question should be quite obvious, but I cannot find it. I have a edmx file that has one table. There is a field of type string. EF always generates nvarchar for that (which is kind of expected), but I need an ntext instead of nvarchar for that field as 4000 is too small for me.
So tell me - what is the proper way to tell EF to generate ntext fields?
PS Using Entity Framework 4, SQL CE 3.5
I guess you are using model first, don't you? You can simply create custom T4 template for SQL DDL generation and include logic which will use NTEXT when field is defined with max size.
Default template is on:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGen\SSDLToSQL10.tt
Just copy this template and find the logic where data type is created. Once you have your template change DDL Generation Template in model properties (in the designer) to your modified version.
There is much more you can do with generation template because you can add some annotations to your model (XML) and use them for custom logic in the SQL generation process.
Just set the property "MaxLength" in the Designer to "Max". This will generate a ntext field in the SQL CE DB.
If your project contains an ADO.Net Entity Data Model (.edmx) then see Ladislav's excellent answer.
But if you're using the Code First libraries and your project doesn't contain a .edmx then you can use the System.ComponentModel.DataAnnotations.ColumnAttribute to specify the column type:
using System.ComponentModel.DataAnnotations;
public class Note {
[Column("Note", TypeName="ntext")]
public string Note { get; set; }
}

ADO.NET Ef4- How can i map a entity to stored procedure without mapping to table

We are using ado.net entity framework 4.0 for our database layer and I am a newbie to ado.net entity framework. I have created entity via adding a entity in entity framework. I want to map that entity with stored procedure only not table of the database. Stored procedure will return same column as entity. How it is possible and how i can do that without mapping to table?
Here is a complete walkthrough http://msdn.microsoft.com/en-us/library/cc716679.aspx
Its not possible because an ObjectSet is an IQueryable and mapping an ObjectSet to stored procedure would not give u an IQueryable because stored procedures by their very nature cannot be composed. The best you can do is take the content inside the stored procedure and put into a view and map the view to an ObjectSet which is possible.
You need to create a complex type, not an entity. Open up the model browser and import your stored procedure as a "function import" (your SP must not use #tempTables but you can use #tableVariables instead); in the function import wizard you'll see a "create complex type" button.
The SP becomes a method in the model context and you can use it to get IEnumerable[TheComplexType].
In EF4.1 code-first it's even simpler, you put a [ComplexType] attribute on top of any class and you can use that type as a return type for context.ExecuteStoreQuery[T]. If your properties are named exactly as the returned columns are (and the types line up), the mapping is "magic" - it just works.