many-to-one with multiple columns - c#

I have a legacy data base and a relation one-to-one between two tables. The thing is that relation uses two columns, not one. Is there some way to say in nhibernate that when getting a referenced entity it used two columns in join statement, not one?
I have a similar table structure
TaskProgress
ProgressId
TaskId
AssignmentId
UserId
Tasks
TaskId
AssignmentId
TaskName
Each task can be asigned in different assignments. That mean that unique task for task progress can be founded only by AssignmentId and TaskId fields.
I'm trying to use this:
References(x => x.Template)
.Columns()
.PropertyRef()
But can't get how to map join on multiple columns, any ideas?

I'm assuming from your use of PropertyRef in the sample code that the two columns do not form a composite primary key. If that's the case, then you're out of luck because property-ref can only accept one property. Judging by the comments in issue NH-1722, this functionality apparently available in Hibernate but has not been ported to NHibernate.
Update:
The schema you added looks like a many-to-many with additional data relationship between Task and Assignment. TaskProgress is the link table between Task and Assignment. If TaskProgress did not have the additional UserId field then you could model this as a simple many-to-many. Because the linking table has additional data it gets a bit more complicated.
Many-to-many with additional data is usually modeling by creating an object representing the linking table (TaskProgress) and modeling the relationship as two one-to-many relationships. That is, Task and Assignment have one-to-many relationships with TaskProgress. TaskProgress has properties for Task, Assignment, and User.

Related

EF6 Table Splitting with foreign keys (Database first)

I'm currently investigating the possibility to use table splitting with EF to stop pulling too many columns for nothing. As for now, I'm able to create a new entity, cut/paste the fields into the sub-entity and map it without much problems.
However, if one of those fields is a FK in the master table, it gives me the following error
"Running transformation: There is no property with name 'IdDocumentImportSource' defined in type referred by Role 'DocumentImports'."
I do understand that the both tables have a NavigationProperties that cannot be resolved anymore by the association FK because the field has been moved to the child table.
Here's my question; Is there a way to automaticaly move the association FK to the child table? I could only make it work by manually deleting the association, both navigation properties, creation the association FK of the child. It involves quite a lot of work on my part if I have to do all this manually for every association FK I got...!
DocumentImports is the ParentTable that I splitted into a new child table DocumentImports_StatusDetail and DocumentImportSources is the table being referenced by the FK.
Thanks!

Code first of EF, how to define navigation property relationship without setting foreign key between table in database

I use code first of Entity framework. There are two classes "Question" and "User". I defined a relationship as below:
this.HasRequired(v => v.Creator).WithMany(v => v.Questiones)
.HasForeignKey(v => v.CreatorId).WillCascadeOnDelete(false);
After gernerating the database I found that it always create foreign key between Id of User and CreatorId of Question. Because of lower performance of FK(and other reason),I want to define navigation property relationship without setting foreign key in database? Delete FK after EF created it?
If cannot do this using fluent api, could you tell me why EF designed in this way please?
About the lower performance of FK. I have a User table with 5 Million records in it. when I insert a Question into db, since the db check the question.CreatorId validation from User table, it always slower than without FK.
And there are many other reasons that I need to remove FK.
I think I am somewhat obsession because I think that deleting FK after created it is strangely and ugly. What i want is implementing this by using something like WithoutForeignKey in fluent api:
this.HasRequired(v => v.Creator).WithMany(v => v.Questiones)
.WithoutForeignKey(v => v.CreatorId).WillCascadeOnDelete(false);
Without questioning why are you trying to do this strange thing and going just to the answer: you could delete fk constraint after generated, or you could use migrations and remove FK generation from the migration code.
SQL code generated when traversing nav properties will work even if fk constraint doesn't exist, except for cascade deleting
If you want a relationship between two tables, you need to define a foreign key. No way around it. Even if you use Map() in fluent api, you can only hide the foreign key in your model, in the background EF will still use it and it will exist in the database.
Also I don't get what you mean by "performance" of foreign key? One extra (likely small) column won't make a difference. If you mean the navigation properties for the performance part, you can do 3 things:
Don't include them in your model
Make them non-virtual to disable lazy loading
Disable lazy loading all together with ctx.Configuration.LazyLoadingEnabled = false;
If you don't want to tell db about relation and treat both entities as not related (I wonder why), then just ignore these navigation properties and FK field. Note that you will be responsible for managing related entities: saving and loading them from db, updating ids etc
this.Ignore(q => q.Creator);
this.Ignore(q => q.CreatorId);
And you also need to ignore other side of relation, otherwise EF will generate FK column with default name Creator_CreatorId. So in Creator entity configuration:
this.Ignore(c => c.Questiones);

What's the proper design for a one-to-one relationship using Fluent NHibernate?

I have a table of Recipes. Each Recipe has one and only one row in table RecipeMetadata, which contains various data about the recipe that I don't want to store in the Recipes table for various reasons. Thus, Recipes and RecipeMetadata have a one-to-one mapping. My Recipes table is as follows:
public partial class RecipesMap : ClassMap<Recipes>
{
public RecipesMap()
{
Id(x => x.RecipeId);
// Map() various columns here
HasMany(x => x.Ingredients).KeyColumn("RecipeId");
HasOne(x => x.Metadata);
}
}
And here's my RecipeMetadata table:
public partial class RecipeMetadataMap : ClassMap<RecipeMetadata>
{
public RecipeMetadataMap()
{
Id(x => x.RecipeMetadataId);
// Map() various columns here
References<Recipes>(x => x.Recipe).Column("RecipeId").Not.Nullable();
}
}
However, when I load a Recipe and access the Metadata property, it attempts to find a row in RecipeMetadata where Recipes.RecipeId = RecipeMetadata.RecipeMetadataId. In other words, it does the join using the primary keys on both tables.
With my table schema, RecipeMetadataId is a key unique only to that table, and has nothing to do with RecipeId. RecipeMetadata has another column, also called RecipeId which has a foreign key constraint on `Recipes. The JOIN should work as:
Recipes.RecipeId = RecipeMetadata.RecipeId
My Questions:
Am I wrong for wanting RecipeMetadata to have its own unique ID, and to use a separate column to link this to Recipes? Obviously, I have a FK constraint as well as a unique index on RecipeMetadata.RecipeId so there's no perf impact. Yes, there's some extra bytes on the disk for storing an arguably unnecessary ID on this table.
I've never seen a table whose primary key also has a foreign key constraint on another table. Is this legit practice? It seems to be the way nHibernate prefers to behave by default. Should I give in and let it have its way?
Provided I don't want to change the database (Though I can be convinced to do so if given a legitimate reason), how can I create the desired one-to-one mapping with this model?
NHibernate has a strict definition of one-to-one relationships. Strict but fair. In NHibernate one-to-one relationship means that the a row in table A always has a matching row in table B.
Right or wrong, that won't work with NHibernate's one-to-one mapping. Note that the model you propose is identical to how a one-to-many relationship would be modeled.
It's legit and enforces the one-to-one relationship.
Since you want the recipe to always have an associated metadata row, I would model it using NHibernate's one-to-one mapping. Alternatively, you can map it as one-to-many but only expose one instance as a property.
See also: Ayende's post on the topic.

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! :-)

Fluent nHibernate Join

I have an entity that maps to a table called Rule. The table for this entity has an FK to another Table called Category. I'm trying to figure out how to pull in a property from Category in my Rule entity. I'm pretty sure I want to use a join in my entity mapping, but I can't figure out how to configure it so that it works. Here is my mapping:
Join("Category", x =>
{
x.Map(i => i.CategoryName, "Name");
x.KeyColumn("CategoryId");
x.Inverse();
});
Here is the SQL that it's generating...
SELECT ...
FROM Rule rules0_ left outer join Category rules0_1_ on rules0_.Id=rules0_1_.CategoryId
WHERE ...
Here is the SQL that I want.
SELECT ...
FROM Rule rules0_ left outer join Category rules0_1_ on rules0_.CategoryId=rules0_1_.Id
WHERE ...
I can't seem to find anything on the JoinPart that will let me do this. Subselect looks promising from the little bit of documentation I've found, but I can't find any examples of how to use it. Any advice on this problem would be much appreciated. Thanks!
"Join" is poorly named. a "join" in an NHibernate mapping implies a zero-to-one relationship based on a relation of the primary keys of the two tables. You would use a join if, for instance, you had a User table and a UserAdditionalInfo table, with zero or one record per User. The UserAdditionalInfo table would likely reference the PK from User as both a foreign key and its own primary key. This type of thing is common when a DBA has to religiously maintain a schema for a legacy app, but a newer app needs new fields for the same conceptual record.
What you actually need in your situation is a References relationship, where a record has a foreign key relationship to zero or one other records. You'd set it up fluently like so:
References(x=>Category)
.Column("CategoryId")
.Inverse()
.Cascade.None();
The problem with this is that Category must now be mapped; it is a separate entity which is now related to yours. Your options are to live with this model, to "flatten" it by making the entity reference private, changing the mapping to access the entity as such, and coding "pass-throughs" to the properties you want public, or by using a code tool like AutoMapper to project this deep domain model into a flat DTO at runtime for general use. They all have pros and cons.

Categories

Resources