How to generate Views using databasefirst and entity framework? - entity-framework

I've been given a Visual Studio solution to get up and running again for development. The project uses Entity Framework database first. When I generate model from database, the sql wants to convert all of the views into tables. I know views should be avoided with EF, but what is the best way to correct this issue given that the developer no longer works for us?
Thanks

There is nothing wrong with using views with Entity Framework. I assume you mean to say when you update from database it is trying to convert the views to model objects. This is totally fine. often times you are required to specify the primary key for the view. By default Entity Framework will try to use every non null property as the key. in the context menu for each property you can toggle this.
Are you getting an error?

I've come to the conclusion that there is not a way to recreate view entities in your edmx back into actual sql server database views. What needs to happen is that you would generate the sql from the model and run that sql in sql server management studio query analyzer. Delete the tables created that should have been views and figure out what query to write to recreate the views in sql server as they should be. Once that's done, the views in your model should be fine and update there after when running "Update from Database".
Say you have two tables - Categories and Products. You want to create a view called ProductsWithCategoryName. When you do update from database and this view gets added to your EDMX file, viewing the XML shows the following:
<EntitySet Name="ProductsWithCategoryName" EntityType="NorthwindModel.Store.ProductsWithCategoryName" store:Type="Views" store:Schema="dbo" store:Name="ProductsWithCategoryName">
<DefiningQuery>
SELECT
[ProductsWithCategoryName].[ProductID] AS [ProductID],
[ProductsWithCategoryName].[ProductName] AS [ProductName],
[ProductsWithCategoryName].[UnitsInStock] AS [UnitsInStock],
[ProductsWithCategoryName].[CategoryName] AS [CategoryName]
FROM [dbo].[ProductsWithCategoryName] AS [ProductsWithCategoryName]
</DefiningQuery>
</EntitySet>
Problem with the above is that the defining query is NOT the query that creates that view. For you to get the proper defining query you must actually edit the EDMX file by hand adding the proper query to it as follows:
<EntitySet Name="ProductsWithCategoryName" EntityType="NorthwindModel.Store.ProductsWithCategoryName" store:Type="Views" store:Schema="dbo" store:Name="ProductsWithCategoryName">
<DefiningQuery>
SELECT dbo.Products.ProductID, dbo.Products.ProductName, dbo.Products.UnitsInStock, dbo.Categories.CategoryName
FROM dbo.Categories INNER JOIN
dbo.Products ON dbo.Categories.CategoryID = dbo.Products.CategoryID
</DefiningQuery>
</EntitySet>
This still will not give you the expected outcome of a proper sql view getting created. Basically EF when going from the conceptual to the database only produces an table per entity and views are simply seen as another entity.

Related

Entity Framework 5 renaming - Database First

I'm using Database First approach and I have table called Campus and when I add to my edmx from SQL Server and I see that it renamed to Campu why is that doing?
I'm guessing that your project is having some table pluralization problems. So when your table Campus is created, Entity Framework is literally reading it as an entity called a Campu that you have pluralized to be Campus.
See this link on how to change pluralization.
But this isn't really a problem right? You can change your model name back to Campus.

Entity Framework - Entity not added to design surface

I attempted to update my edmx file by selecting a table. The tool spit out a info message that said the table did not have a primary key.
The entity did not get added to the design surface but it did get added to the .edmx file. In addition, using the model browser I see an Entities.Store and an Entities. My table got added to Entities.Store, but not to Entities.
I cannot access the table that was "added" in the code.
What do I do?
Steps to reproduce:
Create a SQL table with two columns that are both defined as foreign keys to other tables. Make sure the tables that the FKs point to already exist in the model on the design surface.
Right click and choose Update Model from Database...
Next. Under the Add tab, mark the new table under Tables
Click Finish.
An association will be created and it will be selected on the design surface, but it won't start with FK_, it will just be the name of your table. Go to the Model Browser and look under Entity Types. The table will not be there. Look under Associations and you will see your table name there as an association, but it will look out of place (because of the name).
Entity Framework was too smart for me. It created an association instead of an entity. Odd, but it works for how I need to use it.

Trying to traverse tables from sql database using entity framework targeting .net 3.5 websites

I'm simply trying to get data from two sql server db tables using ado.net entity framework. My code is:
using (Model.Entities e = new Model.Entities())
{
return e.PAGE.First().CONTROL;
}
The database is setup to have two tables, a control table which links to a page table via an 'id' field in the tables (control_id). There is one CONTROL object for each PAGE object.
I keep getting a null value for my return value and I know that's not right.
I can use vis studio and breakpoints to see that there is a PAGE object in 'e' and I can see that there are multiple CONTROL objects in 'e'. This isn't a large database, I just have some sample data in there to ensure that I get this working - so I know that there should be a CONTROL object connected to this PAGE (i've verified this through sql server).
I am very familiar with the general code syntax, I've been using LINQ for a couple of years; however, I have not done much work at all with the entity framework or ado.net 4.
It seems like if I just pull individual table data then it works fine (i.e. e.PAGE.First() .. or .. e.CONTROL.Where(x=>x.someValue.Equals('someValue') ) but if I try to pull by traversing through the tables then I get nothing back (NULL).
Hope that all makes sense.
Some questions for you:
I assume is a 1..1 between PAGE and CONTROL,
Is there a FK called "ControlID" on PAGE?
Do you have a navigational property called "Control" on your "Page" entity in your EDMX?
If the answer to all of the above is Yes, then this should work:
var page = e.Pages.Include("Control").First();
Here, you are returning the First "Page" record, and eager loading the associated control.
The SQL produced should be something like this:
SELECT p.*, c.*
FROM Page p
INNER JOIN Control c
on p.ControlId = c.ControlId

EF4 is throwing an error "Schema specified is not valid"

I'm getting a weird EF4 "Entity Framework v4" error when I do a select on the context:
Schema specified is not valid. Errors:
The relationship 'AnalyzerConfigurationModel.FK_AnalyzerMetadataParameters_AnalyzerMetadata' was not loaded because the type 'AnalyzerConfigurationModel.AnalyzerMetadataParameter' is not available.
The query to generate the error is:
Using context As New AnalyzerConfigurationEntities
Dim EFAnalyzerConfiguration = (From P In context.AnalyzerConfigurations
Where P.Name = analyzerConfigurationName).FirstOrDefault
End Using
The schema is show below.
I've checked the connection strings, multiple times, its not that. Everything looks fine. I'm not sure if the XML that gets generated from this schema is off or not. But looked there too and don't see anything off or different from other properties. Has anyone run into this one before?
I found that if I expanded the EDMX file in solution explorer (VS 2012) and right clicked on each .tt file and selected Run Custom Tool also fixed the issue. This might be easier than de
Also make sure you're referencing project has the EntityFramework installed otherwise the dependent code will get this error.
https://www.nuget.org/packages/EntityFramework
Let me explain this:
The problem is because the system did not find consistency of the columns in database, the entities in the .edmx file and the model class and also the use of the same in the controller class.
So follow the following steps to fix this up:
Go to the database, check all the column names and properties.
Confirm them with the class diagram in the.edmx file. Right-click on the class in which you are getting the error, and select update option for the class. Select the Refresh tab in dialogue (if there is no new column added. if new column is added, you can select the add tab.) and select the relevant objects. Generally they are tables. So select them and finish.
Next check the names in the model class and the controller class.
This should be the solution. If not, let me know.
Are you using the SelfTracking Entity T4 template? I had this issue and found out the T4 template was not re-generating my entities after I had changed the Entity model in the Entity Designer. Try to right click the T4 Template and click "Run custom tool", and see if that helps.

Entity framework - "Problem in mapping fragments"-error. Help me understand the explanations of this error

Error 3007: Problem in Mapping Fragments starting at lines 186, 205: Non-Primary-Key column(s) [WheelID] are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified.
I found several places on the web describing this error, but I simply don't understand them. (confused smiley goes here)
One
Two
Three
Four
There is something pretty fundamental here, I must be missing. Can you explain it, so that I understand it? Maybe using my real life example below?
Foreign key 1:N Wheels.Id -> Slices.WheelId
I add them to entity framework, and WheelId is not visible in the Slices-entity.
Doing some workaround (deleting the relationship from the db before adding tables to EF - then re-creating it and updating EF) I managed to get the WheelId to stay in Slices, but then I get the error mentioned at the top.
Since Slices.WheelId is an FK, you cannot expose it in your client model, period. There are ways to get the value, though.
var wheelId = someSlice.Wheels.ID;
Update In EF 4 you can do this by using FK Associations instead of independent associations.
Try to remove foreign property column from Entity set using entity model design it will solve your problem
For example
We have two tables one is customer and other one is order, using entity model design we added association between customers and orders when we do this Ado.net entity framework i will add navigation properties to both below tables.
Like
Customer.Orders - Here order is list
Order.Customer
One - Many relation.
So we need to remove property from with name CustomerId[Foreign key column] from Order entity set.
For reference:
http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/2823634f-9dd1-4547-93b5-17bb8a882ac2/
I was able to overcome this problem by the following steps:
right click the designer window
Select 'update model from database'
Select Add AND make sure that the 'Include foreign key columns in the model' checkbox is selected.
click on Finish...
I had set foreign keys up in the database but framework still wasn't pulling them in correctly. So I tried to add the association myself. 
However, when I did this I would get a mapping error. It took me A WHILE but I figured out. What I did was set up the association using the entity toolbox association tool and then you have to double click on the association (1 to many) line and set the primary and foreign key there. Hopefully, this to help others who might have the same problem. I couldn't find the answer anywhere.
I had this problem for quite a different reason, and the message was slightly different; it didn't say "data inconsistency is possible because the corresponding conceptual side properties can be independently modified."
I have a table involved in my model with a binary column where I store image data. I only want this data returned when I need it (performance is a feature), so I split the table using a method similar to this. Later on, I added a property to that table, then updated the model from the database. The wizard added the property to both entity types that refer to the table with the added property. I had to delete it from one of them to solve the error.
I've had this happen because Entity Framework Update wizard mismapped some keys (or did not update?). As a result, some columns were mistakenly labeled as keys, while actual key columns were treated as plain columns.
The solution was to manually open EDMX file, find the entities, and update the keys.
Couldn't get any of the answer to work with EF6. The problem seems to be the framework doesn't import the foreign keys correctly as Associations. My solution was removing foreign keys from the tables, and then manually adding the associations using Entity Framework model, using the following steps: Entity Framework - Add Navigation Property Manually
For LinQ to Entities queries in EF1, my workaround for not having access to the foreign key as a property is with the following code, which does not produce a join query to the associated table:
dbContext.Table1s.FirstOrDefault(c => (int?)c.Table2.Id == null)
i.e, the generated SQL is:
...WHERE ([Extent1].[Table2Id] IS NULL)...
Solution is to allow deleting Rule = Cascade on Sql association.
Same thing as to be done on .edmx model, adding element to
association:
<Association Name="FK_Wheels_Slices">
<End Role="Wheels" Type= "your tipe here" Multiplicity="1">
<OnDelete Action="Cascade" />
</End>
</Association>
I had a table already mapped in EF. I added two more tables which had foreign keys in the previously added table. I then got the 3007 error.
To fix the error I deleted all three tables from the EDMX file, and then re-added them all at once together (via "Update Model from Database..."), instead of in stages.
I checked my Error List window and noticed I had errors in the model. Fixed them and all is well
in my case I solved this error by tick (include foreign key columns in the model)
- update Model from database
- tick (include foreign key columns in the model)
- finish