Entity Framework: how do I add a field to my entity to match the store procedure result - entity-framework-4

I have an entity (Org) in my Entity Framework that has a foreign key with a table that is in another database (BusinessUnit). We need the foreign key to get the description of the BusinessUnit linked with the Org. In the past (old project without Entity Framework) we were using a stored procedure to return all the information about this entity, including the BusinessUnit description, using a join. So now my problem is how to display the same information than before using Entity Framework.
I've tried, once I load my Org entity from database, to make a loop accessing to BusinessUnit to get the description for each Org, but this is too slow. My other idea was use a store procedure, but I need an extra field on my entity and Entity Frameworks gives me an 3004 error: No mapping specified for my property. I was thinking to use a complex type, but I'm not sure if it's what I need keeping in mind I have to add just a field to my entity. In that case, could I use the complex type just for "select" operations and keep my original entity for the rest of CRUD operations?
How should I proceed?
Thanks.

EF is not able to execute queries across multiple databases. If you need to perform such query you must either use database view and map the view as a new entity (it will be readonly - making it updatable requires mapping insert, update and delete stored procedures) or divide your data querying into two separate parts to load data from both databases. Divided querying can either use two contexts or you can get data from the second database using stored procedure.
The reason why you got the error is that you added the property in EDMX. EDMX can contain only properties mapped to your first database. EDMX generates entity code as partial classes If you need property manually populated from the second database you have to create your partial part (partial class) for entity and add the property in code.

Related

Stored procedure in entity framework 4.3 + mvc 4

My application is using ASP.NET MVC 4 and using stored procedure in EF 4.3
I know, in EF if I am passing parent entity only then also I can add child entity with just in one line of code.
But I am confused how can I insert data in parent-child tables using single stored procedure?
What I want to is my parent's table is having primary key and which I want to insert in child table as foreign key. So how can I do this in one stored procedure using EF 4.3
You don't say what your database is or why you want to use EF4.3 in an mvc4 app or why you want to add entities using a stored procedure rather than just let EF do it for you taking care of the foreign key relationship as it does. You haven't said whether you're using a code first approach or using the entity model design tools
The reason why I bring this up is because ordinarily EF can handle creating parent child entities and will return the entities with populated key values by default and it's easier to code than using stored procedures. If you have to use stored procedures than EF6 has better support for stored procedures then EF4 did so if you must use stored procedures then can you upgrade to EF6?
If you are using code first with EF4 then your basic workflow would be to create a wrapper method for your parent entity and child entity each wrapper method accepts an entity as a parameter the wrapper for the parent entity then builds a database command from the entity with parameters populated with values from the passed in entity it then executes the command and the stored procedure command should return the key value of the new parent entity.
You can then update each of the child entities with the foreign key value and then pass each child entity to the respective wrapper method - which in turn needs to execute the relevant stored procedure which will also return the new primary key value for the child
You can then either just update your passed in entity with the new key values or use the key to get EF to fetch the new entity with the key - the latter is preferable if your stored procedure is doing more than just populating db fields ie calculating values etc.
I don't know what you would do or even if you can do this in the designer - I know that the designer in ef4 has better support for stored procedures than code first. But I would expect that if you're hoping to just pass the object graph to a stored procedures imported into the designer then this isn't going to work ( I don't know that you can't I would be surprised if you could) because you need to be able to pass in a collection of parameters for the child entities which in turn could have child entities.

Property in Entity partial class

I have an entity/table that uses sqlgeography.
Since EF 4.X doesn't support spatial types I'm instead sending the bytes of the field back and forth.
I have stored procs on the database side that handles the converstion and properties on the code side to do that job.
To add the properties in the code I used a partial class.
One of those properties is for the SqlGeography which simply wraps around the byte[] property to handle getting and setting.
This property is hidden from EF using the NotMappedAttribute.
The other is the property exposing the byte[] itself and is decorated with the EdmScalarPropertyAttribute and DataMemberAttribute.
I then go to the EF model designer (*.edmx) to point the entity model at the Insert/Update/Delete stored procs.
It finds the stored procs alright and realises that they (when appropriate) take a VARBINARY parameter.
It also has a drop down allowing you to select a property on the entity class which maps to that parameter.
However this drop down doesn't list either of my properties. I don't care about the SqlGeography property since that is meant to be hidden from EF, however it is vital for me to be able to point it at the byte[] property, as that is where the data comes from.
I would very much like to avoid database triggers or wrapper classes and addiitonal fields to fudge this in to working.
I tried manually editing the .edmx file to include the byte[] property, but then it just complains it's unmapped.
Can anyone give me some insight in to how to get this to work? Or an alternative method of achiving the end result?
We could use a view to create the binary field for us, but this then involves manually creating a lot of the xml for the relationships within the data.
This pretty much voids the point of using EF which is to make life simple and easy.
For this project We'll just add a binary field to the table then have sprocs to handle the converstion on the server and a property in a partial entity class for exposing the geography type in the model.
Next project I doubt we'll be using EF. Dapper is so much more painless, even if theres a touch more code writing involved.
Here's the links for using views if anyone thinks it would be applicable to them:
http://thedatafarm.com/blog/data-access/yes-you-can-read-and-probably-write-spatial-data-with-entity-framework/
http://smehrozalam.wordpress.com/2009/08/12/entity-framework-creating-a-model-using-views-instead-of-tables/
In the end we created a computed column for each table that exposes the spatial data as bytes.
We then use stored procs for inserting and updating the spatial data.

Load File using Entity Framework

Right now I have file upload/download through Entity Framework working but I see an issue coming up. In the scenario when i want to get a list of all the files associated with a record, I don't want it to pull the Data property, just the FileId and Name, because the files can be up to 10MB each.
I have LazyLoading disabled so I'm thinking about putting the Data column into another table and only load the data when I want. That way I can just supply a link to a controller with the FileId I want to download. But maybe there is a better way? All suggestions are appreciated. Thanks!
My File entity has the following properties:
FileId
FkRecord
Name
Data
you do not need to put data column in another table - just create another entity in the designer and move you [Data] column in it. don't forget to create corresponding table mapping in designer - map you data column to the column in db table.
Also create 1 to 1 association between entities. And you could use navigational properties and do not need to alter you db table!
I found similar discussion:
Can I lazy load scalar properties with the ADO.Net Entity Framework?

Entity Framework 4 Repository returning IList: What C# code could limit which POCO fields populate?

If you populate a drop down list of possible values, you only want the database query to pull two fields, a value and text (like customer ID and Name).
However, your Repository returns POCOs, namely the entire Customer record.
I wouldn't think you should create a POCO for every single DDL list you need, so how does one specify to a repository what fields to populate using Entity Framework 4, ASP.NET POCO generator, and a repository that doesn't return IQueryable or IEnumerable (doesn't defer the SQL call when leaving the repository)?
Simply put, how do you inform the repository to only populate some fields of your POCO?
I bet you could use an internal class to pull out different content, then AutoMap them to your Domain Models before you leave the Repository. It would mean duplicating classes though.
Otherwise you could return IQueryable from your Repository, which has all kinds of problems, like querying a set of data when you .Count then again when you use the data.

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