Entity Framework Overhead - entity-framework-6

I am building an application that will interface with my database backend using EF 6. I have my database built so I will be going the database first approach.
One of the goals will be to utilize the grid control from DevExpress and allow the user to view a Master/Detail style of information for each Facility in my Facility table.
I need the ability to update/insert so I would assume using a view would not be as good as actually supplying the context to the grid's data source.
My question is trying to understand the overhead involved with Entity Framework. If my table contains 20 columns but my Grid only needs 10 of these for viewing/updating/inserting does the application still load ALL of the information into memory? Am I better off using a view for the grid and some form of custom routines for an update?

It doesn't necessarily load all of the columns. If you're smart about it, you can only have it load those columns that you need using LINQ to Entities.
For example:
var records = db.MyTable.Where(...Some condition...).ToList(); will return all the columns.
But doing it this way
`var records = db.MyTable.Where(...Some condition...).Select(x => new MyModel { ...some fields here... }
will only load those fields that are specified.
I've worked with DevExpress and Entity Framework combined before, and I can tell you that it's relatively painless as long as you understand what you're doing with Entity Framework, and don't just blindly have your grids make queries that can get expensive.

Related

How to insert 200 rows into database from Entity Framework in one hit

In my MVC 5 application with EF 6.0, I want to insert 200+ records of Product into database using Entity Framework in one hit.
[1]One way is to convert list of records into XML and pass to Stored procedure.
[2] If I use DbContext.Add() , this will fire for every record ( create insert script internally).
[3]If I traverse list of product and pass each record to Stored Procedure, I think this is also not good.
What is the best way to do this?
I'm not sure if this question How to pass a table-value parameter will work for you but it is exactly what I'm using to load data into a SQL 2014 data base. Very nice and has been working for 4+ years.
Disclaimer: I'm the owner of the project Entity Framework Extensions
(This library is NOT free)
This library can make your code more efficient by allowing you to save multiples entities at once. All bulk operations are supported:
BulkSaveChanges
BulkInsert
BulkUpdate
BulkDelete
BulkMerge
BulkSynchronize
Example:
// Easy to use
context.BulkSaveChanges();
// Easy to customize
context.BulkSaveChanges(bulk => bulk.BatchSize = 100);
// Perform Bulk Operations
context.BulkDelete(customers);
context.BulkInsert(customers);
context.BulkUpdate(customers);
// Customize Primary Key
context.BulkMerge(customers, operation => {
operation.ColumnPrimaryKeyExpression =
customer => customer.Code;
});
I have several productive Web applications that use EntityFramework.BulkInsert library with this NuGet package. It works fine, but it is no longer maintained, so a better solution is to use the updated version EntityFramework.BulkInsert-ef6-ext.
It is very simple to use:
context.BulkInsert(yourListOfModels);
and it generates BULK INSERT Sql commands that run much faster that classical Enrity Framework individual INSERTs.

Core Data: Which record loads by default in core data if you do not specify which one?

I have a static table for settings where I want to pull some stuff from an entity in Core Data. The use case does not lend itself to a table of records as you usually see. Rather each row of the static table is really a field related to the user--as in a user profile. I have a feeling that in testing I may have created more than one record in the entity. I know there are programs that let you see the SQL lite database underneath, but my question assumes you do not have this tool and are relying just on Xcode.
My question is when you have more than one record in a Core Data entity/table, and you try to load data from the managed object context into a VC, one field into one element, what record is shown by default?
Related to this, if you don't know how many managed object or rows are in the database, is there anyway to specify which record you want since there are no auto ids as you would use in a traditional database?
The record that gets loaded from the fetch first. Depending on your sort that might be consistent or it might be random.

ASP.net MVC dynamically alter database structure and update model

I am in phase of designing architecture of my web application. I want to work with asp.net mvc5 and oracle database at back end.
One basic requirement of my project is that the application's admin users can add/remove Form Fields. I want to physically add/remove columns in my database tables at run time (not design time).
How can I achieve it in mvc and how the models can be updated dynamically at run time?
Should I use some ORM or how I design data access layer for that?
I just need suggestions and hints for the architecture design approaches.
Instead of physically adding and removing the fields at runtime you can try the following table structure
Field Name Field Type
CustomField1Name Nvarchar(256)
CustomField1Value Nvarchar(Max)
CustomField1IsVisible Bool
CustomField1FieldType Nvarchar(32) [char/numeric/bool etc]
CustomField1Required Bool
CustomField2Name Nvarchar(256)
CustomField2Value Nvarchar(Max)
CustomField2IsVisible Bool
CustomField2FieldType Nvarchar(32)
CustomField2Required Bool
If you need any more field specific information like custom validation you can add here.
Repeat this for how many custom fields you want . Due to this design, in run time there will be no structure changes in DB level. All changes you can do in coding level.
Entity attribute value pattern is one way to go. In my opinion this becomes an anti-pattern if overused. This has some shortcomings such as storing every value as a string. You might find it hard to parse "true+" as a bool. You could also do this in a weakly typed fashion or weakly typed datasets. If you want to go this route you would actually be creating columns. Do not give users rights to create columns, give them rights to execute a proc that creates columns.

Using EF and MVC together

I would like to use Entity Framework 5 from which I can use one MVC Model that can span two or more databases.
Is this possible?
In other words, have one EF model that can use two or more databases. Because with MVC, you can only use 1 model in a View. Some of the data with some of the Views can come from different databases. In order to use the model binder in MVC and map it to EF 5 columns, I would need to accomplish this.
ASP.NET MVC is NOT dependent on Entity Framework.
ASP.NET MVC is a framework for building web application that stick with the Model View Controller pattern. It is not bounded to Entity framework. It can work with any data access technologies like LINQ2SQL / Entity Framework / Pure ADO.NET etc.. that means you can develop MVC application with or without using Entity Framework.
I assume you want to get data from 2 different databases and load a model object. You can do that by writing a select query which gets data from 2 databases and put that in a Stored procedure and put that proc in your database which your DbContext is communicating with. Then execute the stored proc and load the Model object.
a sample procedure which gets data from 2 databases
CREATE PROCEDURE GetCustomer(#id int)
AS
BEGIN
SELECT C.ID,A.DateReceived
FROM FirstServerName.DbName.dbo.Customer C
INNER JOIN SecondServerName.DbName.dbo.Applications A
ON A.CustomerID=C.CustomerID
AND A.CustomerID=#id
END
To execute the stored proc with Entity framework, you can use Database.SqlQuery method
var idParam = new SqlParameter { ParameterName = "#Id", Value = 414};
var result = context.Database.SqlQuery<Customer>
("exec GetCustomer #Id", idParam).ToList();
This will execute your proc and load the data to an instance of Customer class, assuming the result set structure and your model class structure look similar.
You may need to adjust the permissions of the stored proc to read data from the relevant databases /tables.
What Shyju is saying is that MVC doesn't care or know anything about your Entity Framework data model or database. As such, the idea that an MVC model can span two databases is like saying an airplane can span two hammers.
As above the M in MVC is whatever you want it to be. Microsoft don't specify what Model actually is. It certainly doesn't have to be an EF Model (although some code samples from MS use that as an example)
I'd suggest that M should be a ViewModel and should be unrelated to your data layer. Then use a tool like Automapper to map from a domain model to a ViewModel. The ViewModel encapsulates the data you want to show and any specific web view specific information that you want to display. Then when you post back the ViewModel you can use that to update the domain models appropriate fields etc and persist that to both databases. This is a good article on the subject of ViewModels http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/

Model binding to DataTable with no underlying database

I am bootstrapping myself through my very first ASP MVC project, and could use some suggestions regarding the most appropriate (data-side) model binding solution I should pursue. The project is 'small', which really just means I have very limited time for chasing down dead-ends, which cramps my available learning curve. Thanks heaps for reading!
Background: a simple address search app (ASP.NET MVC 3) that sends user form input to a vendor-sourced server, and presents the results returned from the server in a rules-driven format. There is no CRUD-style repository as such; this is an entirely read-only application. The vendor's .NET server API specifies the use DataTable objects (System.Data.DataTable) for both requests and replies.
Currently: I have a prototype under construction to validate server behavior and inform the application's design. There is a conventional MVC data model class for the input form which works great, auto-binding with the view just as you'd expect. When submitted, the controller passes this input model to my vendor API wrapper, which is currently binding to the request table medieval-style:
public DataTable GetGlobalCandidateAddresses(AddressInputModel input)
{
...
DataRow newRow = dataTable.NewRow();
newRow[0] = input.AddressLine1;
newRow[1] = input.AddressLine2;
newRow[2] = input.AddressLine3;
...
dataTable.Rows.Add(newRow);
...
This works fine; the inputs are fixed and have very light validation requirements. However, if there is a modern framework solution for quickly reflecting a DataTable from my model, that would be peachy.
My real conundrum, however, is on the reply. The table returned by the server contains a variable column-set, with any combination of at least 32 possible unordered fields on a per-transaction basis. Some of the column names contain compiler-invalid characters ("status.description") that won't map literally to a model property name. I will also have a need to dynamically map or combine some of the reply fields in the view model, based on a series of rules (address formats vary considerably by country), so not all fields are 1-to-1.
Just to get the prototype fired up and running, I am currently passing the reply DataTable instance all the way back to a strongly-typed view, which spins it out into the display exactly as is. This is nice for quickly validating the server replies, but is not sufficient for the real app (much less satisfying best practices!).
Question: what is my best tooling approach for binding DataTable rows and columns into a proper model class for display in a view, including some custom binding rules, where no underlying database is present?
Virtually all of the training materials I am consuming discuss classic database repository scenarios. The OnModelCreating override available in the Entity Framework seems ideal in some respects, but can you use a DBContext without a DB connection or schema?
If I have to roll my own model binder, are there any tricks I should consider? I've been away from .NET for a while (mostly Java & SQL), so I'm picking up LINQ as I go as well as MVC.
Thanks again for your attention!
Create a poco display model AddressDisplay and do custom object mapping from the data table to the display model. You can use data annotations for formatting but you can also do that in your custom mapping. You shouldn't need to create a custom model binder.
So create two poco models, AddressInput and AddressDisplay, you can use data annotations on AddressInput for validation. When AddressInput is posted back, map it to the outbound data table. When the response is received, map the inbound data table to AddressDisplay and return the view to the user.

Resources