Entity Framework 6.x: Customize Fluent API in Code First to an Existing Database - ef-code-first

I have installed the EntityFramework.CodeTemplates (as replacement for the previously used Entity Framework Power Tools) and I am struggling to customize the T4 runtime scripts from the files EntityType.cs.t4 and Context.cs.t4 (executed when adding a new "ADO.NET Entity Data Model" to the project and selecting "Code First from Database"). For instance I would like to customize the fluent api code generation and change for instance the property names in the EF entities, to be different from the column names from the mapped tables (which is default).
...
modelBuilder.Entity<Department>()
.Property(t => t.Name)
.HasColumnName("DepartmentName");
...
Another customizations that I would need is to be able to change the entity name (to be different from the mapped table name), or to change the names of the different navigation properties between tables:
...
modelBuilder.Entity<Department>()
.HasMany(e => e.NavigationPropertyName)
...
The default code generation of the fluent api code occurs through the MethodChain() helper methods, called at different parts of the Context.cs.t4 runtime script.
I am stuck with the customization of the t4 scripts, as I did not found any samples how to add some additional fluent api code to the default generated fluent api code in MethodChain(). Can anybody post some samples about how this kind of customizations could be done ?

Related

Audit.Net Entity Framework - Independant Associations [Tables Many-To-Many]

Hi i write because i have configured the Audit for one single table for all my entities and its working fine for the general tables in my model, but with the Many-To-Many tables i don't know how can i do for setup the "AssociationEntryRecord"? the event is fired by EF when i do one change in this tables but i don't know how saved!
Could you please help me with this questions, thanks in advance for your help & the library...
For configuring the Entity Framework event provider use the fluent API provided by Audit.EntityFramework.Configuration.Setup()
You can include the associations as follows:
Audit.EntityFramework.Configuration.Setup()
.ForAnyContext(config => config
.IncludeIndependantAssociations());
And about your sample code (what you should have included as textual code and not as an image):
The first line is not needed, since the UseEntityFramework() will
override the DataProvider
The primary key value can be calculated as: entity.TablePk = entry.PrimaryKey.FirstOrDefault().Value.ToString();

Use FOSUserBundle in relation with yml-based Entities

I've started a Symfony2 project from scratch where I then installed FOSUserBundle.
Then, I have written (actually, generated with ORM Designer) some entities that need to have relations between them, and with the User entity.
I have Items belonging to Users, Collections belonging to Users that group Items, and so on.
Since I used FOSUserBundle I only have a basic User class (https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/index.md , step 3a) defined using annotations, no config/doctrine folder and no User.yml file in it.
I then created the MyBundle/Resources/config/doctrine folder and added the yml files mentioned above.
When I try to generate the entities with the command-line tool everything works fine: it will create the Entities from my yml files.
However, at this point, trying to load up in browsers the url where the login previously worked (when I only had the FOSUserBundle installed) will throw this error:
MappingException: No mapping file found named
'/var/www/concert/src/X/MyBundle/Resources/config/doctrine/User.orm.yml'
for class 'X\MyBundle\Entity\User'.
Following actions, such as generating the CRUD logic, will not work as long as I have an *.orm.yml file in the config/doctrine folder. If I remove those, CRUD generation will work, but generation of actual mysql tables won't.
Juggling with these gets me to a point where I can also get the tables, but then the actual app doesn't work if I try to use any of the url's where the newly generated CRUD is involved because since the entities are based on yml (which I remove to get things "working") it won't have any mapping knowledge.
Is this inherently wrong? To have yml-based entities in relationship with an User entity based on the FOSUserBundle and still be able to get the nice command-line generation tools?
The problem you describe stems from mixing configuration formats (yaml and I assume annotations). You can easily fix this by ditching the annotations in your models and replacing them with yaml-files like you would do in your own models.
Unfortunately the FOSUserBundle-docs only show you how to use annotations, so here is a quick transformation into yaml format when your X\MyBundle\Entity\User extends FOSUSerBundle's UserEntity:
X\MyBundle\Entity\User:
type: entity
table: fos_user
id:
id:
type: integer
strategy: { generator: "AUTO" }
The remaining stuff is taken care of by FOSUserBundle, as the BaseModel is a mapped-superclass and already describes the stuff in the User.orm.xml, but you could just as well replace the existing values or add additional values just like you would do with your own models.
If you don't use annotations throughout your app, you might also want to disable them in your app/config/config.yml to prevent side effects.

Creating blank dummy Components which contain mandatory Fields with the SDL Tridion 2011 Core Service

I wanted to create a blank Component in SDL Tridion 2011 using the Core Service. The only information I have at the start of the process is the Schema URI. The Schema may contain any kind of field (text, rtf, number date, embedded etc), some of which may be mandatory.
I understand that for the mandatory fields, I will need to save some dummy value in them, and this is acceptable as they will be changed manually later.
How can i achieve this?
First - you make sure all fields are set to optional in the schema, otherwise this will never work.
Second - You save.
When an optional field has no value, it will have no XML representation. If you have a schema that defines a component like this:
Field1
Field2
Field3
When all fields are optional and you save a value in Field 2, Tridion will store the following:
<Content xmlns="yourNamespace"><Field2>SomeValue</Field2></Content>
If one of your fields is not mandatory, then you'll have to provide a value. If you're using the CoreService then you can use ReadSchemaFields class to get the fields and some information about them - what type, mandatory/optional, etc.
Looking at your question/requirement to understand what you're exactly looking for, so we can answer the best possible and relevant.
Are you asking for "How can you write a generic code for component creation using core service?" instead of creating a component with a specific schema knowing all the fields upfront.
If that is what you are looking for, here is what you need to do:
You need to read the schema fields with CoreService (since you know the schema URI)
Now you know what type of fields (embedded/component link etc) you need to create content for
use the links pointed by "Puf" in his answer.
Please note that, if the field is marked as required in Tridion Schema you must have to fill a value and it has to match the field type defined in schema.
Reading schema fields via Core Service sample code can be found here
Updating a Component's field through the Core Service is already answered here: Updating Components using the Core Service in SDL Tridion 2011
That post points to a helper class you can find here: Updating Components using the Core Service in SDL Tridion 2011
If those don't help you in creating a Component, I suggest you post your code instead of asking us to write it for you.
We ask about use case, because code to fill in specific fields for a specific schema only works in one environment. Code that can automatically determine fields is re-usable.
If the use case is for an Tridion setup that has Inline Editing (Experience Manager or SiteEdit), then the correct approach is content/component types. These define a reference component with "junk defaults," instructions to the author, and even save location context.
If the use case is to allow authors the ability to create dummy components, this is out-of-the box with:
CTRL+C
CTRL+V
One-time setup required to create a "reference component." Of course we can mimic this behavior (in case "Copy of Untitled" isn't an appropriate name) by copying items with the core service.
In that case, I'll also do a copy--see a general solution for creating Tridion items using the Core Service.
Fields that require a default can have an actual default in the schema.
"Junk values" don't help authors much, always consider good defaults such as an appropriate selection or instructions in the case of fields (maybe). A 10 second change costs development practically nothing, but impacts all future components and the authors that create them.

Generating entity class files from table schema

I am using LINQ to SQL with C#.
Is there a method through which we can generate entity class files from the table schema?
By dragging tables onto the graphical designer classes are generated but they are not the real class files(i mean actual files with the extension cs).
I am aware of that we can code the class files first and then create the schema manually or programmatically, but i wanted to know if the reverse is possible, may be using some third-party tools. I feel it will be very convenient to use LINQ that way.
Thanks in advance.
I'm not as familiar with LINQ to SQL as I am with Entity Framework (v4), but EF certainly would fit your requirements. You can download the POCO templates for EF from Microsoft, right through VS2010 in the Extension Manager (Tool > Extension Manager, click on Online Gallery, and search for POCO). The link is not just the download for the template, but a walkthrough on how to get started.
I also have started a series of blog posts that include some nice T4 templates for an Entity Framework EDMX model that auto generate DTO classes for all of your entity classes, whether you're using the default code generation model, or Microsoft's POCO template. The auto generated DTOs are handy for use in UI or service layers, and save you from having to bring in dependencies on Entity Framework in consuming layers. It's also very easy to get DTOs from your entity objects.
var people = from p in context.People select p;
return people.ToDtos();
Might be worth a look (shameless self promotion).
If you need/want to stick with LINQ to SQL, do a google search for "linq to sql POCO", it seems some people have had a degree of success with this, but most of the search results seem to be from 2008 and earlier, so I'm not sure about currency / relevancy.
All the classes generated when you drag tables to the designer are created as partial classes. There is no reason you can't just create a file for each one and use that to make the necessary modifications.
Absolutely you can, if you use the T4 template for L2S - http://l2st4.codeplex.com/
You still use the .DBML file, but you need to set the "build action" to "none" on the file to turn off the compilation of the default code that gets generated. Then you add the .tt file and the .ttinclude file from your codeplex download.
The T4 template has a line of code in it that you can modify to suit your purposes:
FilePerEntity = false, // Put each class into a separate file
Oddly, Entity Framework 4 is using this approach too with the dual methods of generating the code from the model file, but with EF, the T4 template is included with VS2010. With Linq-to-sql, you have to download the T4 template separately. The nice part with using T4 is you can add other customizations as you go. However, initially the code that's generated is identical as what you got from the .DBML designer.

Error using ASP.NET Dynamic Data Filtering with Entity Framework

I have just added the Dynamic Data Filtering library to an Entity Framework based Dynamic Data web application, but on trying to access List.aspx, I get the following error. Is there anything I can do about this on .NET 4?
The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.
I've had that problem one without Dynamic Data Filtering library.
I solved it by using the project template: dynamic data entities web application.
I found the solution on the page
http://blog.davidyack.com/journal/2008/5/21/dynamic-data-choosing-the-right-template.html
I've run into this error too. Just add an OrderBy before the Skip in your query, just like it says.

Resources