Entity Framework - am I doing it wrong? - c#

I'm having a hard time getting Entity Framework to do what I want it to do. I've got a form generator application that's already up and fully running in .NET WebForms. I've just begun the process of converting this over to use .NET MvC instead, with React as the view layer and Entity Framework to drive the database stuff.
One part of this application is intended to allow the users to add form controls to a list and have them laid out visually as they would be shown on the final published form. So you click on First Name, and it adds an input control with ID FirstName, header text above it, etc.
I've got the view layer set up to show some basic info about the controls and put them into a list. I've also already got all the database tables with the assembled information about various types of controls you can add to the page. My WebForms version of this manages all the relationships between various data tables and how that is packaged for the view layer through code.
I've been trying to use my existing tables in Entity Framework but haven't been able to get any of the foreign key relationships to work correctly. When I add them in MS SQL, they don't carry over and give me ways of accessing the data from the foreign tables via the objects representing a main table.
When I just leave the tables without any foreign key relationships in SQL itself
and add them to the model in Visual Studio, it also won't sync up the objects correctly. It will throw errors relating to missing mapping or that it can't find the data in the foreign objects.
So I've reached the point where I am importing all my tables, which does work correctly, but then I have to update the model for each table to add an object or collection of objects that can contain a reference to the corresponding matched foreign key data. Then I have to write procedures which will go through and set the object references themselves according to ID columns which already exist in the database (ControlType in Controls table matches up to ID in ControlTypes table, etc.).
Then if I make a change in the database and update the model, it will remove all the custom objects I've added to the model, and possibly throw more errors to boot if I've removed a column on the database. What a headache!
So I know that seems like a wall of text, but I'm at a loss for what to do. I'd like to just have a big data object that I can pass around for each control that contains all the related info pertinent to that particular control and can be used by React in my view layer to display the info.
An alternative to that is I could build in Ajax requests into the various components which would make database calls to get the info relevant to that particular portion of the control, but that seems like a huge pain.
Am I going about this all wrong or is EF really just this hard to use?

Related

Updating Sql , through a view via wpf and ef

Background
I am starting a series of simple screens to display and update info in our ERP database.
I have worked through the wpf controls and understand the need for Observable Collections and after reading around on Entity Framework I understand the advantages of it sitting on top of ADO.net compared to the basic SQL methods and Datatables I am more comfortable with due to my SQL experience.
When I tried EF when I was first started working with Data CRUD screens I struggled to get the Observable Collections I needed, but having read this walk through last night ( https://msdn.microsoft.com/en-us/data/jj574514.aspx) and seen the notes for VS 2010 to edit EF code to get Observable Collections I think I want to try EF again.
Question
My Data screen needs present information which has be combined from five tables and a couple of sub views to be meaningful to the user.
Included in the dataview is a simple Y/N flag which comes from one of the five Datatables.
Can the user update the Y/N flag through the view mapped to EF, displayed in WPF datagrid ?
Or do I have to map all the base Datatables and sub views and recreate the view and Data Context in EF to allow the update to work?
If it is the latter does any one know of any tutorials or walk through I can use on my test development to try EF please
Thanks
The user can update a field via the view mapped to EF, however it is a little bit more complicated.
For a single table mapped to EF, the update is done by EF automatically, for a view mapped to EF you need to define the update function in the mapping details.
The function would be in form of an SQL stored procedure mapped to EF.

ADO.NET Entity Data Model refresh after incremental Db changes

I am using VS 2013 Express for Web with ADO.NET Entity Data Model.
When updating the entity data model from database using 'refresh' tab option (seems you can only select one item though the heading says select objects plural) the usage seems unclear and I have noticed some issues.
Just two examples:
I changed a stored procedure so it returned the same number of fields but one field was of a slightly different type but the complex type never changed. I realise there can be an impact on client code but this simply did not change the complex type, everything stayed the same. However, removing the relevant elements from the model browser then readding the elments from the database back into the model did exactly what I expected.
I made some significant changes to two or three tables, attributes and one relationship but did bot change the table names. Here again refresh had some very odd results, so I simply created a fresh model.
I am planning some more changes first change specifically I am adding a FK relationship that I forgot.
Is there any way to be sure of what is supported and what is not in terms of refresh.
Also I am concerned that if refresh fails and I so delete the two tables with the relationship, what impact will that have on temporarily orphaned tables and their relationships, and if when I regenerate the two tables their connections with the other tables will still work. I guess it depends how the generated code works underneath.
I want to make these kinds of changes but avoid have to recreate the entire model.
Any advice appreciated.
The most guaranteed way of ensuring you always have the latest version is to select all (Ctrl A) delete, and then re-add everything from the model page.
I know it sounds like a pain but it's guaranteed to work as long as you haven't made any changes to the model from within Visual Studio.
The refresh doesn't always work.

View using same type as Table

I have a table that used throughout an app by Entity. I have a view that returns an identical column set, but is actually a union on itself to try to work around some bad normalization (The app is large and partially out of my hands, this part is unavoidable).
Is it possible to have Entity 4 treat a view that is exactly like a table as the same type, so that I can use this view to populate a collection of the same type? This question seems to indicate it is possible in nhibernatem but I can't find anything like it for entity. It would be an extra bonus of the navigation properties could still be used to Include(), but this is not necessary (I can always manually join).
Since EF works on mappings from objects to database entities this is not directly possible. What you need is something like changing the queried database entity dynamically, and AFAIK this is not possible without manually changing the object context.
For sure the EF runtime won't care as long as it can treat the view as if it was completely separate table. The two possible challenges that I forsee are:
Tooling: Our wizard does allow you to select views when doing reverse engineering (i.e. database-first). Definitively if you can use 'code first against an existing database' you can just pretend that the view is just a table, but you won't get any help scripting the database creation or migrations.
Updates: in general you can perform updates for a view setting up store procedure mapping (which is available in the EF Designer from v1 or in Code First starting in EF6). You might also be able to make your view updatable directly or using instead off triggers (see "Updatable Views" here for more details). If I remember correctly the SQL generated by EF to retrieve database generated values (e.g. for identity columns) is not compatible in some cases with instead-off triggers. Yet another alternative is to have your application treat the view as read-only and perform all updates through the actual table, which you would map as a separate entity. Keep in in mind that in-memory entities for the view and the original table will not be kept in sync.
Hope this helps!

c#: Dynamic DAL with changing table structure

I am facing one problem. I am working on a project which has requirement of dynamically populating Grid control to add, update and remove records of specific table.
database is not finalized yet. so what i want is, if i add new column to a table and run the application. that grid should contain newly added column so that i can add new row. update or delete existing row.
I have crated DAL using LINQ to SQL but that is not covering my requirement. I want
Get name of tables from database and show them in dropdown list.
after selecting table name. grid should populate with all the columns. so that i can add/update/delete records.
So what exactly is your problem, you want to know how to get the table list from the database? If it is so, and if you're using SQL Server, you could run a select like that :
select name from sysobjects where xtype = 'U'
You can explore this system tables : sysobjects and syscolumns, they store the metadata information on the database.
From what I can gather, your best bet would be taking a different approach than Linq to SQL. You are looking for a UI which directly reflects your domain and can be generated automatically / dynamically. Two methods come to mind:
You can leverage MS Dynamic-Data which is an ASP.NET WebForms-based technology. You wire it up directly to a database or Entity Framework model. It generates the grids for all CRUD operations. It detects relationships via foreign keys and can generate the tables with links to one another. It's very customizable.
Dynamic Data
There is another architectural pattern called "Naked Objects". This requires rich, well-designed domain and aggregate roots. The UI should be 100% generated from this domain model. See the videos on this site to get a great example.
One example I can give you is, recently, our team has been divided - some working on an SOA application which integrates with our main product. Our developer resources are all focused on the task at hand writing WCF services, architecture, database engineering, ASP.NET, etc etc. We needed an internal application which we could use to administer the new SOA application. We could not dedicate another group of guys to build out a new application.
By using Dynamic Data, we had the entire administration app up and running off our EF 4 model in no time. It's doing everything we needed and minimal resources were exerted.
Use ADO.NET Entity Framework for your DAL than using LINQ TO SQL.
Well I solved this problem by getting table info from database schema.
build table to grid on run time which auto generates all columns.
created insert/update/delete query on fly by getting columns name from grid column name.
Happy coding:)

How can I use the EntityModelSchemaGenerator to generate less then my entire model?

We have a big (and growing!) database. We're trying to not have to build the models by hand, and we found this
EdmGen2 which is supposed to build our EDMX entity models for us.
Since we have such a big database we'd like to not have all of our tables in the same Model. We got it all to work, but the generated model has all of our tables.
There is a read only list of the tables inside of the EntityStoreSchemaGenerator. It is (in fact) all of our tables.
Will this tool make a model that is less then our full database? Can we select which tables we want to put it and only use those?
The EdmGen2 code comes with an option called /RetrofitModel. The key point of this mode is that is runs some data mining algorithms to see if there are any obvious inheritance-like relationships in the database instance, and if so, generates an EDMX that includes those inheritances.
However, another feature of the /RetrofitModel option is that it allows one to select tables. For instance, if one has the AdventureWorks sample database, you can issue this statement:
EdmGen2 /RetrofitModel "Server=(local);Integrated Security=true;Initial Catalog=AdventureWorks;" "System.Data.SqlClient" "AVWorks"
It will bring up a list of the tables in the database, at which point you can check which ones you want to have in your model.
The tupleFraction parameter helps define what it means to be a "significant" subclass. The data mining rules are heuristics, and as such they can potentially find patterns where common sense might not agree.
The tupleFraction parameter says this (for some of the rules): if EdmGen++ thinks that it has found a subclass, but the new subclass has less than tupleFraction of the instances from its parent class, consider the new subclass "insignificant" and don't create it. The parameter is optional - if you don't specify it, I think that it gets set to 0.05 (5%).
The current version only allows table specification through the UI. However, to pull the list of tables from a file or from some other source is an easy addition - I will add it to the top of the to-do list for the next version.
UPDATE: We have updated the code at code.msdn.microsoft.com/edmgen2 to allow for tables to be specified without the GUI. In the previous version, the RetrofitModel option would bring up a dialog that would allow the user to choose the tables to include in the model. The ConceptualEdmGen dll now has two additional public methods that can set the list of tables without bringing up a dialog – one that pulls the list of tables from a file, and one where the list of tables is fed directly to the method as a list of strings.
The EdmGen2 code as it appears in the package uses the “from file” option, where it looks for a file called “Tables.txt” in the current directory, and if found, feeds its contents to the dll to set the list of tables. So for instance, if the following were the contents of the file “Tables.txt”:
HumanResources.Department
HumanResources.Employee
HumanResources.EmployeeAddress
HumanResources.EmployeeDepartmentHistory
HumanResources.JobCandidate
HumanResources.Shift
EdmGen2 would generate (for the RetrofitModel option) a model for all of the tables in the HumanResources schema for AdventureWorks. For both methods, an empty list will result in all tables in the database being added to the model. The table selection UI will still appear if neither table selection method is called.
I've just sent an email to the guy responsible for EdmGen2 lets see what he comes back with
Alex James
Program Manager, Entity Framework Team, Microsoft.
My solution to this was to create a variant of EdmGen2 which reads a Filters.txt file that contains not just table names, but text that gets parsed into EntityStoreSchemaFilterEntry parameters (Category, Schema, Name, ObjectType, FilterEffect). This allows me to generate models and assemblies which operate on specific views as well as tables - something that I don't think EdmGen2 does.
Of course that doesn't work with the ConceptualEdmGen, but since there is no source available for that I've elected not to use that component anyway.
One problem that I haven't solved is how to properly inject function definitions for stored procs into CSDL and MSL. I have it in SSDL but don't know yet how to do the others.

Categories

Resources