EF 4.1 code first with Existing Database.Mapping Fks,table etc.Clarification needed - mapping

I am learning code first and I have project to be used with an existing database.
I am a bit confused of what I meant to be doing.I will explain:
Do I need to create an entityconfiguration for each table in my existing database?
Within this EntityConfiguration for each table do I need to create foreign key relationships?
Do I need to do a ToTable for each table in my existing database?
Is there any free tool "codeplex" that pointing to an existing db will generate this codeFirst stuff?
I have seem few blogs about "EF Code first with existing db" but I am not sure or was not clear to me If Need to create this stuff or I will be getting strange errors like "MyColumn_MyColum" basically as if codeFirst is trying to build some FKs or something.
can somebody clarify?
thanks a lot. I know there are few questions but if you can answer 01 or 2 that would be fine.
thanks again

If you want the code to be generated for you use database-first approach with DbContext API. Simply create EDMX file from your database and let DbContext Generator template generate all entities and context for you.
DbContext Fluent API is mainly targeted to the code-first development approach where EF will created database for you from the code you provided. It can be used with existing database but it requires much more skills and understanding of mapping wich EF can provide to you.
Generally:
You don't need to provide EntityConfiguration for each table if you follow some naming conventions (entity name is singular form of table name, all properties have the same name, primary key in table and entity is named as Id or EntityNameId, etc.).
You don't need to define relationships manually if you follow conventions with exposing navigation properties and possibly also foreign key properties. The issue can be naming of many-to-many keys and junction tables.
ToTable is needed only if your entity does not follow naming convention or if you map some advance inheritance or splitting.
EF uses a lot of default conventions which drive how the names should be defined. Conventions can be removed.
You will not do anything wrong if you define EntityConfiguration for each table - it will at least allow you learning what is needed and your mapping will be explicit / self documented.

Related

Can EF6 use an existing table with GUIDs as the join/bridge table?

I have an existing database and one of the tables for the existing webforms application is a join or bridge table called PostCategory that links up Posts and Categories but it uses GUIDs to do that. It has GUIDs for CategoryID and PostID. When I tried use fluent mapping to point EF at that table I got the error that only ints can be used.
So I suspect the answer is no but I wanted to ask in case someone has done it. According to this post, it is possible with NHibernate but not EF.
This is not possible with EF because it doesn't support unique keys. Only primary keys can be used as principal in relation.
Now the post is from 2012 so I though maybe something has changed with EF6.

EntityFramework database vs model

I understand the fact that generating a model based on the DataBaseFirst method woill produce a collection of entitites on the ORM that are essentially mapped to the DB tables.
It is my understanding, that if you need properties from other entities or just dropdownlist fields, you can make a ViewModel and use that class as your model.
I have an AppDev course that I just finished and the author wrote something that if I understand it correctly, he is referring to change the ORM entities to fit what your ViewModels would look like, hence, no need for ViewModels. However, if you do this, and regenerate the ORM from the database, those new entities that you placed as "ViewModels" would be gone. If you changed the ORM to update the database, then your database structure in SQL Server would be "undone".
Please inform me if my understanding is correct that I simply need to use a ViewModel in a separate folder to gather specific classes and or properties in a superclass or a single class with the properties that I just need and use that as my model....
Here is the excerpt from the author:
EntityFramework is initially a one to one mapping of classes to tables, but you can create a model that better represents the entities in your application no matter how the data is stored in relational tables.
What I think the author may have been hinting at is the concept of complex models. Let's say, for instance, that in your Database you have a Customer Table and an Address Table. A one to one mapping would create 2 model items, one Customer class and one Address class. Using complex model mapping, you could instead create a single Customer class which contained the columns from both the Customer Table and the Address table. Thus, instead of Customer.Address.Street1 you could refer simply to Customer.Street1. This is only one of many cases where you could represent a conceptual model in code differently than the resulting data in storage. Check out the excellent blog series Inheritance with EF CodeFirst for examples of different mapping strategies, like Table Per Hierarchy (TPH), Table Per Type (TPT), Table Per Concrete Class (TPC). Note that even though these examples are CodeFirst, they still apply to Entity Framework even if the initial models are generated from a Database.
In general, if you use DatabaseFirst and then never modify the resulting entities, you will always have a class in code for each table in the database. However, the power of Enity Framework is that it allows you to more efficiently work with your entities by allowing these hybrid mappings, thus freeing you to think about your code without the extra burden of your classes having to abide by rigid SQL expectations.
Edit
When the Database-First or Model-First entities are generated, they are purposely generated as partial classes. You can create your own partials which extend the classes that are generated from Entity Framework without modifying the existing class files. If the models are re-generated, your partial classes will still be intact. Granted, using partials means that you have the Entity Framework default behaviors as well as your extended behaviors, but this isn't usually a huge issue.
Another option is that you can modify the TT files which Entity Framework uses to generate your models, ensuring that your models are always regenerated in the same state.
Ultimately, the main idea is that just because the default behavior of Entity Framework is to map the database to classes 1:1, there are other options and you are never forced into something that isn't efficient for your project.

Is there a way to undo /remove / rollback EF 4.3 foreign key naming convention?

Using EF code first, we have a db seeding framework that uses dependency injected Db initializers and seeders to populate a dev db with sample test data.
Some of these seeding operations need to import a lot of data, so for a couple of tables, we use actual SQL files with INSERT statements. For some of those insert statements, foreign keys must be diabled then re-enabled:
ALTER TABLE [Schema].[TableName] NOCHECK CONSTRAINT [TableName_FkPropertyName]
-- perform a block of inserts
ALTER TABLE [Schema].[TableName] CHECK CONSTRAINT [TableName_FkPropertyName]
I just updated from EF 4.2 to EF 4.3 and noticed that these no longer work. An examination of the db created by EF shows that the FK's are now named differently:
FK_CodeFolder1.Table1Name_CodeFolder2.Table2Name_DbFkColumnName
Is there any way to remove this naming convention and go back to the original? If not, how is this not a known issue or breaking change?
Update after Ladislav's Reply
Ladislav is right, my above explanation of the new naming pattern was not quite right. I have updated it. The part preceding the . was not the full namespace, but it was the name of a folder in the entity model project. So if I had an entity WidgetAbc in folder AggregateSet1, the fk pattern fragment would be AggregateSet1.WidgetAbc, not just WidgetAbc.
Why do you think it is an issue or breaking change? IMHO it is EF internal behavior - you are using code first and in this approach you were not supposed to work directly with database and especially you were not supposed to base your custom database scripts on hardcoded names because you don't have control over their generation.
I don't think you can revert the behavior but you can start using migrations and code your table definitions - AddForeignKey method should allow you naming your FK constraint.
Btw. I see different naming pattern of FK constraints in EFv4.3:
FK_DependentTableName_PrincipalTableName_FKColumnName

Changing entity name/poco class name from table name while creating model from the database

I want to create a entity model from the existing database but all the table names contain "_"/underscore in the database so while creating poco classes i want remove underscore from name of the entities/poco classes. Is there a way to change the naming convention while the entities are created in the entity framework during the creation of model from database
Thanks,
Amit
You have two options,
There is a little bit of a learning curve but it involves using T4 templates to do the code generation yourself. Basically you would just strip out the _ in the conceptual model. guide to customizing entity classes
Easier, and a little more painful is to just import your model and then use the model explorer and rename each entity. You will only have to do this once, it will save the mapping from conceptual to physical. A walk through can be found here (search for "Changing an entity name")

How to get the foreign key in Entity Framework?

I am developing StudentApp in .NET 3.5 SP1 MVC Application.
I have two tables
Course
CourseID, course_Name
Students
studentID, student_Name, courseID(fk)
Now I made StudentApp.dbml which is having both table as entities.
As Foreign key will not be present in student entity,
I can not display courseID in student model, more over i can not generate add, edit, list views.
So tell me how to display courseID(fk) in student & i also want course name instead.
And also dropdownbox showing course name & storing courseID in edit view .
I'm pretty sure you have to load the foreign reference for each entity. Since I have no idea how you've constructed your API, I'll have to give you a pseudocode'ish example, but I think this is what you need to do.
List<Students> studList = [your_db_facade].SelectStudents() // Or however you retrieve your students
foreach (Students singleStudent in studList)
singleStudent.Context.CourseReference.Load() //CourseReference.Load() should be in the framework
Then you get the CourseID and name from the single student entity like
singleStudent.Course.CourseID
singleStudent.Course.course_Name
It could look slightly different for you, but I think the key to solving your problem is CourseReference.Load().
If your using LINQ-to-SQL and created a DBML file in Visual Studio then the foreign keys can be listed through the Course property in the Student object (automatically generated so since it is a one-to-many relationship from Student). Sort of like this:
var studentCourseIds =
from s in context.Students
select s.Course.CourseID;
Since your goal is to find the coursename then it is already accessible with Student.Course.course_Name.
Can you post your DBML? Also, DBML is used in LINQ to SQL (L2S) - EDMX is the mapping used in the ADO Entity Framework. Are you using LINQ to SQL or the Entity Framework (EF)?
No matter which one you are using - they both support Foreign Keys and you would get a property representing either side of the relationship - you don't need to do anything special (the Foreign Key must exist in the database, of course).
In EF, the foreign keys are called "navigtion properties" and they work a little differently to Foreign Keys in L2S. Nothing major, but updating them and "eager loading" are somewhat different.
Just drop the tables onto the map in the designer in Visual Studio (or generate using command line equivalents if you prefer).
Regarding Foreign Keys and Drop Down Lists (and other UI goodness) - I wrote a couple of blog entries on some approaches which might suit you. One part is located here and part two is located here.
if you create the correct relationship in your SQL server database, then when you add the tables to your DBML designer, the relationships will be copied across also and your code will link up automatically.

Resources