Generating entity class files from table schema - asp.net

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.

Related

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

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 ?

Re-Scaffold views after changing their model

I'm using Visual Studio 2013 and ASP.Net MVC 5. I've created a bunch of views for my models and then I've changed them. I want to run scaffolding on some models and create some views automatically and then change the automatically-generated views. Is there another way other than re-naming some files or creating another solution and copying stuff?
Yes, you can re-scaffold by scaffolding the same model again, using the same model class and controller names as before. Your existing controller and views will be replaced.
Details:
Right click on your project or controller folder,
Add ... New Scaffolded Item,
MVC 5 Controller with views using Entity Framework,
Add
Choose your model and data class,
And ensure your controller name is the same as the one to replace.
I use version control - GIT to do it quickly and safely. I use Git Extensions (http://code.google.com/p/gitextensions/) user interface for git.
Have your code commited before re-scaffolding. Then re-scaffold the views, and go to staging (the button Commit in Git Extensions). It shows all changes that re-scaffold made and colors the new and deleted code lines. From there you can stage only the selected new lines, that changed in controller. After staging selected lines, reset the unstaged other changes.
There you have it! Your already modified code with new scaffolded parts. Do any edits and testing necessary and commit.
This is a new answer to an old question. It's somewhat similar to the existing answers, but I think different enough and easy enough to be of value.
1) Save the existing project/solution to version control just as good practice.
2) When re-scaffolding, use a different controller name which will create a controller class and it's 5 attendant views, but it won't overwrite anything that exists, preserving all your existing work.
3) Extract the appropriate methods from the re-scaffolded controller. Bindings for create/edit will likely change when the model changes, so capture those. Then delete the re-scaffolded controller.
4) That leaves the views in place to copy and paste the appropriate UI code for any new or redefined model properties. Once all the code needed has been copied, simply delete the re-scaffolded views.
It was a great question because we often have to change a model, and it's nice to have all the basic UI stuff automatically created for us.

Updating Role description (entity framework / LINQ)?

Mates, I want to update a role description using my application
I donĀ“t know what is the better way to connect to the database and run a UPDATE statement.
Would it be Entity Framework? LINQ? None of this 2 options..
Please, suggestions.
I would say that Entity Framework would be currently the best solution for you. Not only it is strongly supported by Microsoft (well Silverlight was as well) but:
If you start with it, you can use designer. It's graphical UI will guide you when generating the model (based on database) or generating the database schema when starting with model.
Read some tutorials abut it:
http://msdn.microsoft.com/en-us/data/ee712907
And later take a look how to use some more profesionla techniques as Repository pattern or unit of work
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
Not Linq ..well yes linq, but linq is the querying framework where as entity framework is the object relational mapper. So Both actually. You could do this in various other ways but those two technologies work very well together from my experience.
In Visual studio you would create a new ADO.NET project template which you then hook up to your database. and then you can update the tables and do a whole bunch of stuff. Linq is build into .NET so technically you can query any objects using linq ( which makes it so much fun ) and because your entity is an object you just reference it ( first declare it ) and then play with it
FooModel foo = new FooModel(); // Entity
var fooQuery = from _ in foo.DescriptionTable // Linq query
where _.Description == SelectedDesc // table selection query
select _;
foo.Add(fooQuery); // add to database
foo.SaveChanges(); // save changes
Something like that. There is a bit more to it that would project specific but you would have to give more details.
It is most certainly worth learning both technologies and have doubt you will find them very useful. Both can get very complex but for what you need it for you just need the basics down and then you can explore from there.

MVC3 with EF Dbfirst, how to generate "controller with read write actions and views"

I am learning MVC3 and EF with DB first approach.
In some videos of MVC3 with code first approach from Scafolding Options they choosed "controller with read write actions and views" and after selecting Model and Data Context classes some code was automatically generated.
In my working I have a separate class library which has EF model in it (please see blue selected area in diagrame) . Please guide me how to access that EF and its generated classes to use with controller with read write actions and views ?
EDIT
I am adding new Controller.
I am not getting the comments you mentioned in your picture.
I am getting some classes in Model Classes drop down but not my EF classes are there in list.
I have not done any refrencing to class library in my MVC project. Please guie me how and what where to do ?
Thanks
I believe you're referring to MVC Scaffolding
Install-Package MvcScaffolding
If it shows No Model Classes availble, when you hover it will give you a more verbose description:
If you get this message, cleaning and rebuilding should fix your problem.
Is your database project referenced by your main project? In your main project click references, add new reference - then in the projects tab select the name of the project with your edmx:
After that, clean and build!

Entity Container and Model generation in different assemblies

I'm doing some refactoring and am trying to reuse my genertated entity models. My application has a few assemblies, one being my outward facing public types (API) and one containing implementations of providers (such as the log).
I'd like to split the generation of the entities and models so that the entities will be in the API assembly and the container will be in the implementation assembly. Is this possible?
Is possible. This is how I did it.
Assembly A
Database.EDMX
Models.TT
Models.cs
Assembly B
Database.EDMX (Added as a Link to the real file in Assembly A)
EntityContainer.TT
EntityContainer.cs
That's how everything is laid out. These are the rough steps:
Right click on the EDMX in A (public API assembly) and Add Code Generation File
Adds a TT to the project. Called it Models, as it will contain the models only.
Edited the TT and removed code generation for entity containers
In assembly B (internal implementations) added Database.EDMA as a link
Opened in assembly B, right click and Add Code Generation File
Adds a TT to project B. Called it EntityContainer as it will contain that only.
Edited TT to do the following
Removed entity creation steps
Changed the path to Database.EDMX to a relative path pointing at the original copy in A
Added a using for my models
Hopefully this will all compile and work correctly (I'm still far from getting everything compiled and tested). Looks good so far.
Additional change:
In my entity container TT, I had to modify the definition of the EscapeEndTypeName to the following:
string EscapeEndTypeName(AssociationType association, int index,
CodeGenerationTools code)
{
EntityType entity = association.AssociationEndMembers[index]
.GetEntityType();
return code.CreateFullName(
code.EscapeNamespace(association.NamespaceName), code.Escape(entity));
}
I'm using association.NamespaceName as it contains the correct namespace from the other assembly.
I don't know the answer, but I think that your question is essentially equivalent to "Is it possible to cause a T4 template in one project to emit code into a different project?" If you can do that, then you can do what you want. Note, though, that this is substantially easier in EF 4.
So I think you might get useful feedback if you asked that question directly.

Resources