Creating a custom entity with the Entity framework - c#

If I have for example two entities, lets say Customers and Staff with no relation between them, is it possible to create a third entity which doesn't have a corresponding table in the database which takes some information from the first and the second entity and also one or two additional columns (for example computed columns)?

You can join entities through this: http://blogs.msdn.com/b/simonince/archive/2009/03/23/mapping-two-tables-to-one-entity-in-the-entity-framework.aspx
But I do believe they have to be related; otherwise, how would it know what information was correctly tied to each other? The only thing it could do is query all rows of one entity and match them up with all rows of the other, which is probably not what's desired.

Related

Same model in more than one table

I have a class, suppose it's called EntityModel, and I want to make three different tables with the same columns, as defined in EntityModel. Let's call the tables tbPast, tbPresent and tbFuture. I want also to access them separetely in the Entity DbContext:
using (var db = new MyContext())
{
var element = db.Past.Find(id);
db.Past.Remove(element);
db.Present.Add(element);
db.SaveChanges();
}
The main purpose of having three tables is performance: the table will have millions of rows, and the most important is the Present, with dozens of rows. Most queries will be made in the Present table.
What is the best way to do this? Implementing three models with the same properties doesn't seem right for me.
I'm using Entity Framework, with the Code First approach, along with ASP.NET MVC 3.
You can't use the same model to generate separate tables w/ EF code-first. If you need to have some sort of grouping, use a Discriminator field and assing it any of the values: Past Present Future.
Edit:
Similar effect can be achieved through table-per-concrete type inheritance. Thus each type will have it's own table and can share most (if not all) of the fields.

How can I manage ids of entities in Linq2SQL?

Such a task: we have 2 tables in our L2S Entity classes. It needs to manage with current fields of current tables by numbering em somehow.
Exact question is How can I point to the exact field of exact table without using entity relation names? Such as TmpLinqTable[2] instead of TmpLinqTable.TableField.
Moreover if it can be managed by ids of the entity, not the table.
So my understanding of what you are trying to do is to log changes that happen to your entites. Is that correct? You might want to look into the GetModifedMembers method on the Table class. Here's an interesting link...
http://geekswithblogs.net/steveclements/archive/2008/04/15/linq-to-sql-property-changed--changing-logging.aspx

Entity Framework 4 and SQL Server 2008 Multiple Possible Foreign Keys

I am trying to come up with a database design that would work with Entity Framework 4 Code First. Actually, I have no experience yet of EF4 Code First but as I understand it, if I write the code, it will create the database and tables.
The issue is this. There are various types of auctions, they all have some common fields and some specific ones. In the code I envisage having a base abstract class called Auction and subclasses like LowestUniqueBidAuction and EnglishForwardAuction etc.
Nothing surprising there. The problem is that I imagine the database structure to mimic this. I imagine an Auction table and a LowestUniqueBidAuction table and a EnglishForwardAuction table. In the Auction table I imagine a foreign key into one of these two tables for each row depending on the type of auction that that row is. I also imagine another column in the Auction table with the name of the derived auction table (such as EnglishForwardAuction).
The problem is that whenever I've ever created a foreign key I've had to specify the name of the foreign table into which the key points (which makes sense). In this case, however, there is one of many tables that the key could point. So there are many issues here. Firstly, I could simply not use a foreign key and just use an ordinary field, but then the database will not be able to maintain data consistency for me. The second issue is how will EF Code First handle this? In other words, how will it know that if I ask for all EnglishForwardAuction rows from the Auction table that it should look at the column with the table name and then join on the EnglishForwardAuction table to get the extra fields?
Has anyone ever faced similar issues?
Thanks,
Sachin
This problem is solvable in Entity Framework in a number of ways - read up on how EF handles inheritance and what strategies are available.
There are basically three strategies how to handle this:
(1) Table per Hierarchy
You have only one single table, that represents all possible sub classes. Of course, this means, several rows (that only exist in a given subclass) must be nullable, since they don't show up / don't exist in super classes or other subclasses.
(2) Table per Type
Each subclass gets its own table, and by default, the sub-types table shares the PK with the base classes' table - e.g. PK = 1 in Auction will also be PK = 1 in EnglishForwardAuction. So your subclass tables reference the base table - not the other way around.
(3) Table per Concrete Type
Each concrete subclass (your separate auction types) gets its own table, but that table contains everything - all the columns, from that specific type, but also its base type.
Read more here:
Inheritance in the Entity Framework
Inheritance and Associations with Entity Framework Part 1
Entity Framework Modeling: Table Per Hierarchy Inheritance
Entity Framework Modeling: Table Per Type Inheritance
Searching for Entity Framework Inheritance and/or one of these strategies will reveal a lot more hits, too - that topic is very well covered and discussed on the interwebs! :-)

Reading several tables from one single Entity Framework ExecuteStoreQuery request.

I have a library which uses EF4 for accessing a SQL Server data store. For different reasons, I have to use SQL Server specific syntax to read data from the store (for free text search), so I have to create the SQL code by hand and send it through the ExecuteStoreQuery method.
This works fine, except that the query uses joins to request several tables aside the main one (the main one being the one I specify as the target entity set when calling ExecuteStoreQuery), and EF never fills up the main entity's relationship properties with the other table's data.
Is there anything special to do to fill up these relationships? Using other EF methods or using special table names in the query or something?
Thanks for your help.
Executing direct SQL follows very simple rule: It uses column from the result set to fill the property with the same name in materialized entity. I think I read somewhere that this works only with the the main entity you materialize (entity type defined in ExecuteStoreQuery = no relations) but I can't find it now. I did several tests and it really doesn't populate any relation.
Ok so I'll write here what I ended up doing, which does not looks like a perfect solution, but it does not seem that there is any perfect solution in this case.
As Ladislav pointed out, the ExecuteStoreQuery (as well as the other "custom query" method, Translate) only maps the column of the entity you specify, leaving all the other columns aside. Therefore I had to load the dependencies separately, like this :
// Execute
IEnumerable<MainEntity> result = context.ExecuteStoreQuery<MainEntity>(strQuery, "MainEntities", MergeOption.AppendOnly, someParams).ToArray();
// Load relations, first method
foreach (MainEntity e in result)
{
if (!e.Relation1Reference.IsLoaded)
e.Relation1Reference.Load();
if (!e.Relation2Reference.IsLoaded)
e.Relation2Reference.Load();
// ...
}
// Load relations, second method
// The main entity contains a navigation property pointing
// to a record in the OtherEntity entity
foreach(OtherEntity e in context.OtherEntities)
context.OtherEntities.Attach(e);
There. I think these two techniques have to be chosen depending on the number and size of generated requests. The first technique will generate a one-record request for every required side record, but no unnessecary record will be loaded. The second technique uses less requests (one per table) but retrieves all the records so it uses more memory.

Mapping data from 2 tables to 1 entity - Entity Framework 4

I am stuck here.
Is it possible to map data from 2 different tables to 1 entity in Entity Framework 4.
I have a bunch of employees in one table, and in the other I have som project information.
I would like to combine these 2 tables in one Entity, and keep the tracking features etc., is that possible?
I do not want to use a function import, but do it solely through the Entity Model.
Can anyone help - when I try to do it, i get the following error all the time:
Error 3024: Problem in mapping fragments starting at line 2354:Must specify mapping for all key properties (MyProjectTable.PSInitials, MyProjectTable.ProjectID) of the EntitySet MyProjectTable.
Both key are mapped to their respective tables.
The new Entity are made with MyProjectTable as the basetable.
The relation between the 2 tables is a 1-*
Hope you can help.
/Christian
You cannot map two tables with a one-to-many relationship to one entity. If you don't want projecting the results into one object in code, consider creating a view and mapping it instead.
According to http://msdn.microsoft.com/en-us/library/bb896233.aspx
You should only map an entity type to
multiple tables if the following
conditions are true:
The tables to which you are mapping share a common key.
The entity type that is being mapped has entries in each
underlying table. In other words,
the entity type represents data
that has a one-to-one correspondence between the two
tables; the entity type represents an
inner join of the two tables.
The reasons for doing this are quite straightforward - for example, a table of data points that all have one of five 'types'. Obviously the 'type' will be a separate table for the sake of normalisation, but from an application point of view (working with the data) it makes more sense to have all properties in a single entity.
So we can't do this with Entity Framework - a supposed Object-Relational-Mapper. What, then, is the point of using such a framework?

Categories

Resources