Bind Scalar Property at DataEntity(DataEntity Framework) - c#

folks, i am new to C# DataEntity Framework.
I have 2 tables in DB :
Vehicle with fields id, measurementId.
Measurement with fields Id, Name.
They related as one to one. One vehicle have one measure.
I want to expand entity Vehicles where i want to store MeasurementName field. I've created property MeasurementName, but how i can bind it to Measurement.Name. Is it possible in DataEntity framework ?
I know that i can achive it another way, for example using Entity Linq where i will create new
class Test
{
Id= id,
Measurement = measurement.Name
};
But is it possible to expand DataEntity to have this property ?

Each of the entities in your model is implemented as a partial class, meaning the total code that defines the class can exist in multiple files but gets compiled into one object. This makes them highly extensible as you can add properties and functions to the code generated by the Entity Framework designer. Create a new partial class with the same name as your entity in the same namespace and add the custom property like so
public partial class Vehicles
{
public string MeasurementName {
get {
return this.Measurement.Name;
}
set {
this.Measurement.Name = value;
}
}
}
If this answer was helpful to you, please be certain to vote it up or mark it as the accepted answer.

Related

How do I add multiple tables using one model and one view?

I want to have a page where the user selects from a drop down list the category, then adds a small text about that category and uploads an image where the path of that image is saved in the database rather than the whole image. I have created a table "Categories" where the admin is authorized to fill it and the user only selects from the categories list.
Here is what I have done so far:
The create categories model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace DemoIdentity.Models
{
public class CategoriesAdmin
{
public int ID { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "category name")]
public string categoryName { get; set; }
}
public class DefaultConnection:DbContext
{
public DbSet<CategoriesAdmin> categories { get; set; }
}
}
Now I want to have another table (Data) which includes (ID, Category (category name selected from table categories), News, Image_Path). This table is in the Default Connection database. The category name is the selected category name from a drop down list, and the image path is an upload image which saves the path rather than the whole image.
I am unsure of how to achieve this.
It appears that you are confusing components of ASP.NET MVC and Entity Framework.
As the Entity Framework site states:
Entity Framework (EF) is an object-relational mapper that enables .NET
developers to work with relational data using domain-specific objects.
It eliminates the need for most of the data-access code that
developers usually need to write.
And the MVC site states that:
The ASP.NET MVC is an open source web application framework that
implements the model–view–controller (MVC) pattern.
The two frameworks meet through your model classes. MVC uses the model class to define the data, logic and rules of the application. In Entity Framework, your model class is mapped to tables in your database where it handles the direct reads and writes for you.
By creating your CategoriesAdmin model class and exposing it as a property in your DbContext class as such:
public class DefaultConnection:DbContext
{
public DbSet<CategoriesAdmin> categories { get; set; }
}
Entity Framework will have mapped your model class to a database table called CategoriesAdmins. If this table does not yet exist in your database, it will automatically create it for you. This approach in Entity Framework is known as Code First to a new Database.
Now since you already have a table that stores the available categories (CategoriesAdmin), you will need to create a second model class (called Data for the sake your example) which contains properties for the other bits of information that you want to store.
public class Data
{
// gets or sets the ID of this Data record.
public int ID {get;set;}
public string ImagePath {get;set;}
// other properties
...
}
Now that you have two model classes, you need to create a relationship between the two. In a SQL database this is achieved by Foreign Keys. In Entity Framework, you can achieve the same by using Navigational Properties.
So we update the Data model class as such:
public class Data
{
// gets or sets the ID of this Data record.
public int ID {get;set;}
public string ImagePath {get;set;}
// gets or sets the ID of the related CategoriesAdmin record.
public int CategoriesAdminId {get;set;}
// gets or sets the related CategoriesAdmin record. Entity Framework will
// automatically populate this property with an object for the related
// CategoriesAdmin record.
[ForeignKey("CategoriesAdminId")]
public virtual CategoriesAdmin CategoriesAdmin {get;set;}
// other properties
...
}
The ForeignKeyAttribute on the CategoriesAdmin property is there to give Entity Framework a further hint of the foreign key column to load the navigational property from.
Finally to be able to use your new Data model class with Entity Framework, you need to add another property to your DbContext class so that you have a means of accessing your data:
public class DefaultConnection:DbContext
{
public DbSet<CategoriesAdmin> Categories { get; set; }
public DbSet<Data> Data { get; set; }
}
Now that you have created your model classes and wired them into Entity Framework, you will now be able to use them in MVC. If you load your Data model into your view (using DefaultConnection.Data), you will be able to access the related CategoriesAdmin record by accessing the CategoriesAdmin property on the Data object.
In short: two tables means you need two models. Both models can be loaded into the single view.
Footnote: Apologies if there are large gaps in my answer as there is a lot to explain that have already been explained in other places far better than what I can. The references I have linked should hopefully fill in the gaps.
Should you need more help, please see all of the tutorials on the ASP.NET MVC website on working with data. They're much better written than my concise attempt. I would recommend following them exactly and getting the examples to work before completing your own project so that you have a better understanding of how the two frameworks work and interact with each other.

Entity Framework add property to partial class that will get model or list of models from database

I have added a property to a partial class of a model. This property will retrieve a model from database according to property value.
Example:
class movie
{
int language;
}
partial movie
{
public Language SpokenLanguage
{
get
{
var currLang = db.Languages.Where(ml => ml.ID == this.language).FirstOrDefault();
return currLang;
}
}
}
Is this approach will affect application performance when I retrieve a list of movies?
If so what is the equivalent and better performance?
EF will ignore the SpokenLanguage property in your case.
However, you can make EF retrieve the SpokenLanguage using a INNER JOIN by adding a relation in your model between the two tables.
You can also make it retrieve the SpokenLanguage lazily (on demand)-it will actually make a better version on what you wrote, but if you are sure you want to print the language label in your view, it's better to retrieve it using a INNER JOIN.

Adding a property to entities class, how I can avoid writing all properties again?

I have used Entity Framework and it generated some entity classes for me I want to add a property to one of them there are a lot fields and attribute inside it, when I am going to add property to entity class I have to make child class which is inherited from my entity class then I am usually write this and it works :
IList<newEntity> chid = (from m in db.Entity
select new newEntity
{
//rewrite all properties here
newAttribute = ConvertDate(n.date) //it is example I break it into steps and called some functions to fill new attribute
}).ToList();
My question is how I can avoid rewriting all attribute here it really make me bored to write some code I can just add a new property how I can do that?
I'm not sure if I understood your question correctly, but usually the classes generated by the Entity Framework are partial classes(*), so you don't need to derive from them to add a property. You can add properties, methods etc by adding a class to your codebase with the same name and in the same namespace and then the two definitions are merged by the compiler:
partial class Entity
{
public DateTime newAttribute { get; set; }
}
(*) depending on your code generator

Linq to entities to join two tables

Is there any way to 'join' two DB tables so I could get ID from 1st table then use this ID to get the description from a 2nd table?
For example, the follow query gets the Part ID but I need find the description for this Part ID so I could put the description onto a data grid. I tried to use 'Include' on Web server side but it failed during runtime.
var query = myContext.Get_Table1();
query = query.Where(c => c.Part_ID == '12345');
LoadOperation<My.Web.Table1> loadOp = this.maxContextTransactionHistory.Load(query, QueryCompletedCallback, null);
this.dataGrid.ItemsSource = loadOp.Entities;
I take it that you are using WCF RIA Services? It would have been helpful if you had tagged your question to indicate this.
If this is the case, you will need to use the Include method within your DomainService to include the related entity in the results of the query.
You will also need to apply the IncludeAttribute to the association to ensure that they are marshalled to the client. You can apply the attribute to a 'Buddy' class which is covered here.
In theory it would be sufficient to apply the IcludeAttribute directly to the properties within the generated entity classes. There, they would be overwritten.
The next choice would be in a partial class. Adding another property there with the same signature (so that the attribute can be applied to it) would cause a conflict with the original property.
The solution is to use a new class that is defined within a partial class. The MetadataType attribute is used on the partial class to indicate the class in which its metadata is defined.
The following code will ensure that a Part_Stock's Part_Table is include when it is sent to the client. You will need similar code to cover any other properties that you are interested in.
[MetadataTypeAttribute(typeof(Part_Stock.Metadata))]
public partial class Part_Stock
{
internal sealed class Metadata
{
// Metadata classes are not meant to be instantiated.
private Metadata()
{
}
[Include]
public EntityCollection<Stock_Table> Stock_Table { get; set; }
}
}

how to populate an entity you have extended in the Entity Framework?

I have an entity in my EDMX that I've extended with a few fields in a partial class like this:
public partial class Employee
{
public string JobName {get;set;}
}
These properties are for display only. In the above example say the entity has a JobTypeID property. I wish JobName to be populated w/ the name that belongs to that JobTypeID.
Is there anyway to query the employee record in EF including the value for the JobName property w/o explicity assigning each field using select()?
The reason I ask is that there are a lot of fields in the Employee entity so I'd like to be able to take advantage of something like:
ctx.Employees.Where(e=>e.EmployeeID==employeeID).Single()
...add somehow fill in JobName too
Is this possible?
How about: public string JobName { get { return this.JobType.Name; } }?
Not a solution, but a different approach to what you are trying to achieve...
Why not use the power of EF! use "Include" to load the relation based records from related tables?
You can do that in a single place as well, say if you want a JobType record per Employee record, you may consider using a repository pattern and add all possible includes for your entities which depend on each other!
Some thoughts further on what I mentioned, not exactly as I said but...
http://mosesofegypt.net/post/Introducing-DataLoadOptions-for-Entity-Framework-ObjectContext.aspx

Categories

Resources