Create Self-Referencing Hierarchical Table in Entity Framework - c#

Background
I have a class that looks more or less like this:
public class MyClass
{
[Id]
public long Id { get; set; }
public string MyProperty { get; set; }
public bool MyBoolean { get; set; }
public string AnotherProperty { get; set; }
public MyClass ChildOne { get; set; }
public MyClass ChildTwo { get; set; }
}
I will need to use a stored procedure to load a set of records, but that's ok as long as the structure itself is correct.
For any instance of MyClass, one or both of the children can be null. Any instance of MyClass can be used in a parent class - but the child itself doesn't need to know about this relationship, and a child can be used by any number of parents.
Problem
With this structure, I get the following error when creating a new migration:
Unable to determine the principal end of an association between the
types 'MyClass' and 'MyClass'. The principal end of this association
must be explicitly configured using either the relationship fluent API
or data annotations.
This error makes sense - when given a structure of an object with a foreign key to itself, I am not surprised that EF has a hard time determining the principal end. I'm not sure how to fix this, though.
I've tried some different Fluent mappings:
modelBuilder.Entity<MyClass>().HasOptional(x => x.ChildOne).WithOptionalPrincipal(x => x.ChildOne);
modelBuilder.Entity<MyClass>().HasOptional(x => x.ChildOne).WithOptionalDependent(x => x.ChildOne);
modelBuilder.Entity<MyClass>().HasOptional(x => x.ChildOne);
(Note: I didn't try these concurrently - I did one at a time & duplicated it for ChildTwo.)
I was able to get a migration to work by adding a ChildThree property to MyClass, but that doesn't make sense and isn't a useful property; it just creates another foreign key on the table but this isn't needed in my model.
So, in summary:
How do I get this structure to work the way I want? I think the secret is in some Fluent mapping voodoo but I'm very unfamiliar with that library and I don't know how to get that to work.
Why does adding a third (unneeded, unwanted) property fix everything and allow the migration to scaffold?

Your fluent mapping is totally wrong.
You should do something like this:
modelBuilder.Entity<MyClass>().HasOptional(p => p.ChildOne).WithOptionalDependent();
modelBuilder.Entity<MyClass>().HasOptional(p => p.ChildTwo).WithOptionalDependent();

Related

Mapping One-to-Zero-or-One with EF7

I am currently in the process of cleaning up a fairly large database. Part of the database has a relationship which is a one-to-zero-or-one mapping. Specifically:
User -> UserSettings
Not all users will have user settings, but a user setting cannot exist without the user. Unfortunately, the tables already exist. User has an PK ID. UserSettings has a PK ID and a column, User_Id_Fk which, at this point in time, is not a true FK (there is no relationship defined).
I'm in the process of fixing that and have done so from the DB perspective through SQL and have confirmed with tests. (Added the FK constraint. Added a unique constraint on User_Id_Fk.) This was all done on the UserSettings table. (Note: I am not using EF Migrations here. I have to manually write the SQL at this point in time.)
However, I now need to wire up an existing application to properly handle this new mapping. The application is using ASP.NET Core 1.0 and EF7. Here are (shortened) versions of the existing data models.
public class User
{
public int Id { get; set; }
public virtual UserSettings UserSettings { get; set; }
}
public class UserSettings
{
public int Id { get; set; }
[Column("User_Id_Fk")]
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual User User { get; set; }
}
I have this Fluent Mapping as well:
builder.Entity<UserSettings>()
.HasOne(us => us.User)
.WithOne(u => u.User)
.IsRequired(false);
When I go to run the application and access these items in the database, I get this error followed with a cryptic set of messages that has no information relating directly back to my application.:
ArgumentNullException: Value cannot be null.
Parameter name: navigation
Microsoft.Data.Entity.Utilities.Check.NotNull[T] (Microsoft.Data.Entity.Utilities.T value, System.String parameterName) <0x10d28a650 + 0x00081> in <filename unknown>, line 0
After doing research, someone had mentioned that the ID of the UserSettings class must be the same as the foreign key, like so:
public class UserSettings
{
[Key, ForeignKey("User")]
public int Id { get; set; }
public virtual User User { get; set; }
}
I don't really have this as an option as the DB is being used for other applications I have no control over at this point. So, am I stuck here? Will I just have to maintain a 1:many mapping (which could happen now, though it hasn't) and not have proper constraints for a 1:0..1 mapping?
Update
Looking at octavioccl's answer below, I tried it out without any success. However, I then removed User from the mapping in UserSettings (but I left UserId). Everything appeared to work as far as I can tell. I'm really confused what is going on here, however, and if this is even the right answer, or if I'm just getting lucky.
Remove the data annotations and try with these configurations:
builder.Entity<UserSettings>()
.Property(b => b.UserId)
.HasColumnName("User_Id_Fk");
builder.Entity<User>()
.HasOne(us => us.UserSettings)
.WithOne(u => u.User)
.HasForeignKey<UserSettings>(b => b.UserId);
From EF Core documentation:
When configuring the foreign key you need to specify the dependent
entity type - notice the generic parameter provided to HasForeignKey
in the listing above. In a one-to-many relationship it is clear that
the entity with the reference navigation is the dependent and the one
with the collection is the principal. But this is not so in a
one-to-one relationship - hence the need to explicitly define it.
The example that is presented in the quoted link (Blog-BlogImage) is pretty much the same of what are you trying to achieve.
If the solution that I show above doesn't work, then you should check if User_Id_Fk column allows null. If that is the case, change the FK property type to int?:
public class UserSettings
{
public int Id { get; set; }
public int? UserId { get; set; }
public virtual User User { get; set; }
}

Entity Framework 6 Code First TPH Foreign Key in multiple derived classes

I'm trying to understand what I need to do in order to introduce the same Foreign Key in multiple derived classes when the Foreign Key is not present in the base class. The Foreign Key is to the same type, and I'm able to make the various derived classes all use the same column name, but when I try to introduce the Foreign Key annotation, Entity Framework 6 silently fails to create any Foreign Key at all.
It's worth mentioning that, if I allow EF to create Bar_Name1 instead of reusing the existing column, it adds the Foreign Key appropriately. But I come from a relational database background, and it offends my sensibilities to have multiple columns for the same thing.
I would prefer to be able to stick to using Annotations to mark up my code, but if this is something that can't be done with Annotations but can be done with the Fluent API, I'm willing to delve into that.
public class Foo
{
[Key]
public string Name { get; set; }
}
public class FooSub1 : Foo
{
[Required, Column("Bar_Name")]
public string Bar_Name { get; set; }
[ForeignKey("Bar_Name")]
public Bar Bar { get; set; }
}
public class FooSub2 : Foo
{
[Required, Column("Bar_Name")]
public string Bar_Name { get; set; }
[ForeignKey("Bar_Name")]
public Bar Bar { get; set; }
}
public class Bar
{
[Key]
public string Name { get; set; }
}
The resolution to EF issue 1964 explains: "However, having an association in s-space here doesn't work anyway because it results in two database constraints which can only be satisfied if the dependent also matches the PK for the other relationship type. Such a match would usually only happen accidentally. The solution is to remove the associations from s-space like we do for similar TPC mappings." (emphasis mine)
EF drops the FK's on the merged column. In your case, the two FK's are logically the same, but EF doesn't know (or care about) that.

Implicit Key for a one-to-many relationship in EF code first

I have an aggregate class that will contain a collection of another class, but that class will only ever exist in a collection on that aggregate, so I have no need for an ID on it in my code, or a need for a reference to the aggregate. For example:
public class SalesListing
{
public Guid Id { get; set; }
public ICollection<LocalizedDescription> Descriptions { get; set; }
}
public class LocalizedDescription
{
public string CultureCode { get; set; }
public string Title { get; set; }
}
I'd like to just declare the key for the LocalizedDescription class as a combination of SalesListingId and CultureCode without creating a SalesListingId property or reference back to SalesListing. Any way to do this with EF 5.0 ?
For example, here's an example how I'd imagine such an API would look like if it exists:
modelBuilder.Entity<LocalizedDescription>().BelongsTo<SalesListing>(s => s.Description)
.WithKey((s, ld) => new { s.Id, ld.CultureCode })
No, you will still need to specify an ID
You can define composite keys using the following syntax:
modelBuilder.Entity<LocDesc>().HasKey(ld => new { ld.CultureCode, ld.Title });
That said, I think you will regret not defining an integer primary key. If you ever need to export the contents (such as for an external review or translation), matching records by ID will be faster and less error prone than matching by title. Having the ID doesn't hurt and is easier to include now than to retrofit later.
I think you can specify the FK mapping implicitly by not supplying a specific property for the relation in the mapping definition:
modelBuilder.Entity<SalesListing>().HasMany( e => e.Descriptions ).WithRequired();
Should you need to specify the foreign key property, introduce a SalesListingID property for the value and use the following mapping instead:
modelBuilder.Entity<SalesListing>().HasMany( e => e.Descriptions ).WithRequired()
.HasForeignKey( r => r.SalesListingID );

EF Code First - How to prevent duplicate column on created table on Table-Per-Hierarchy Mapping

I have entity like below
public abstract class MyBaseClass
{
public int Id { get; set; }
}
public class MyConcrete : MyBaseClass
{
public int TemplateName { get; set; }
public int Total { get; set; }
}
public class MyOtherConcrete : MyBaseClass
{
public int TemplateName { get; set; }
public int MyProperty { get; set; }
public string OtherProperty { get; set; }
}
using default initialization, EF will make table with columns like bellow:
Id
TemplateName
TemplateName1 // <-- this is the problem
Total
MyPorperty
MyOtherProperty
now my question how to configure EF so all the TemplateName property on derived class automatically mapped into TemplateName column without making another column. is it possible to configure it on OnModelCreating method?
EDIT
actually above was simplified version of my problem. i have 10 more entities some property might duplicated everywhere and i don't want to add any abstraction layers.
i have tried manually map the column on the OnModelCreating but having "Each property name in a type must be unique. Property name 'TemplateName' was already defined" exception any idea?
EDIT 2
so, i found here, that said it is impossible to do such thing like above in EF, it is weird for me..
Move TemplateName into MyBaseClass to avoid this problem.
If necessary, you can use intermediate base classes to hold properties shared by only a subset of your classes.
After searching through the net, so far that was not possible to do that. since i realize that my inheritance tree is wrong.
so in my case, i should change my code to match the EF requirement, it is sound weird.. because in many case ENTITY is a NO NO to change, we usually create an entity that used in multiple project. event we found our entity wrong we won't update it because updating it will require massive change on the other projects.
so far, i think there is no exact answer for my question. will update it soon after EF support it.

Entity Framework associations with multiple (separate) keys on view

I'm having problems setting up an Entity Framework 4 model.
A Contact object is exposed in the database as an updateable view. Also due to the history of the database, this Contact view has two different keys, one from a legacy system. So some other tables reference a contact with a 'ContactID' while other older tables reference it with a 'LegacyContactID'.
Since this is a view, there are no foreign keys in the database, and I'm trying to manually add associations in the designer. But the fluent associations don't seem to provide a way of specifying which field is referenced.
How do I build this model?
public class vwContact
{
public int KeyField { get; set; }
public string LegacyKeyField { get; set; }
}
public class SomeObject
{
public virtual vwContact Contact { get; set; }
public int ContactId { get; set; } //references vwContact.KeyField
}
public class LegacyObject
{
public virtual vwContact Contact { get; set; }
public string ContactId { get; set; } //references vwContact.LegacyKeyField
}
ModelCreatingFunction(modelBuilder)
{
// can't set both of these, right?
modelBuilder.Entity<vwContact>().HasKey(x => x.KeyField);
modelBuilder.Entity<vwContact>().HasKey(x => x.LegacyKeyField);
modelBuilder.Entity<LegacyObject>().HasRequired(x => x.Contact).???
//is there some way to say which key field this reference is referencing?
}
EDIT 2: "New things have come to light, man" - His Dudeness
After a but more experimentation and news, I found using a base class and child classes with different keys will not work by itself. With code first especially, base entities must define a key if they are not explicitly mapped to tables.
I left the suggested code below because I still recommend using the base class for your C# manageability, but I below the code I have updated my answer and provided other workaround options.
Unfortunately, the truth revealed is that you cannot accomplish what you seek without altering SQL due to limitations on EF 4.1+ code first.
Base Contact Class
public abstract class BaseContact
{
// Include all properties here except for the keys
// public string Name { get; set; }
}
Entity Classes
Set this up via the fluent API if you like, but for easy illustration I've used the data annotations
public class Contact : BaseContact
{
[Key]
public int KeyField { get; set; }
public string LegacyKeyField { get; set; }
}
public class LegacyContact : BaseContact
{
public int KeyField { get; set; }
[Key]
public string LegacyKeyField { get; set; }
}
Using the Entities
Classes that reference or manipulate the contact objects should reference the base class much like an interface:
public class SomeCustomObject
{
public BaseContact Contact { get; set; }
}
If later you need to programmatically determine what type you are working with use typeof() and manipulate the entity accordingly.
var co = new SomeCustomObject(); // assume its loaded with data
if(co.Contact == typeof(LegacyContact)
// manipulate accordingly.
New Options & Workarounds
As I suggested in comment before, you won't be able to map them to a single view/table anyway so you have a couple options:
a. map your objects to their underlying tables and alter your "get/read" methods on repositories and service classes pull from the joined view -or-
b. create a second view and map each object to their appropriate view.
c. map one entity to its underlying table and one to the view.
Summary
Try (B) first, creating a separate view because it requires the least amount of change to both code and DB schema (you aren't fiddling with underlying tables, or affecting stored procedures). It also ensures your EF C# POCOs will function equivalently (one to a view and one to table may cause quirks). Miguel's answer below seems to be roughly the same suggestion so I would start here if it's possible.
Option (C) seems worst because your POCO entities may behave have unforseen quirks when mapped to different SQL pieces (tables vs. views) causing coding issues down the road.
Option (A), while it fits EF's intention best (entities mapped to tables), it means to get your joined view you must alter your C# services/repositories to work with the EF entities for Add, Update, Delete operations, but tell the Pull/Read-like methods to grab data from the joint views. This is probably your best choice, but involves more work than (B) and may also affect Schema in the long run. More complexity equals more risk.
Edit I'm not sure this is actually possible, and this is why:
The assumption is that a foreign key references a primary key. What you've got is two fields which are both acting as primary keys of vwContact, but depending on which object you ask it's a different field that's the primary key. You can only have one primary key at once, and although you can have a compound primary key you can't do primary key things with only half of it - you have to have a compound foreign key with which to reference it.
This is why Entity Framework doesn't have a way to specify the mapping column on the target side, because it has to use the primary key.
Now, you can layer some more objects on top of the EF entities to do some manual lookup and simulate the navigation properties, but I don't think you can actually get EF to do what you want because SQL itself won't do what you want - the rule is one primary key per table, and it's not negotiable.
From what you said about your database structure, it may be possible for you to write a migration script which can give the contact entities a consistent primary key and update everything else to refer to them with that single primary key rather than the two systems resulting from the legacy data, as you can of course do joins on any fields you like. I don't think you're going to get a seamlessly functional EF model without changing your database though.
Original Answer That Won't Work
So, vwContact contains a key KeyField which is referenced by many SomeObjects and another key LegacyKeyField which is referenced by many LegacyObjects.
I think this is how you have to approach this:
Give vwContact navigation properties for SomeObject and LegacyObject collections:
public virtual ICollection<SomeObject> SomeObjects { get; set; }
public virtual ICollection<LegacyObject> LegacyObjects { get; set; }
Give those navigation properties foreign keys to use:
modelBuilder.Entity<vwContact>()
.HasMany(c => c.SomeObjects)
.WithRequired(s => s.Contact)
.HasForeignKey(c => c.KeyField);
modelBuilder.Entity<vwContact>()
.HasMany(c => c.LegacyObjects)
.WithRequired(l => l.Contact)
.HasForeignKey(c => c.LegacyKeyField);
The trouble is I would guess you've already tried this and it didn't work, in which case I can't offer you much else as I've not done a huge amount of this kind of thing (our database is much closer to the kinds of thing EF expects so we've had to do relatively minimal mapping overrides, usually with many-to-many relationships).
As for your two calls to HasKey on vwContact, they can't both be the definitive key for the object, so it's either a compound key which features both of them, or pick one, or there's another field you haven't mentioned which is the real primary key. From here it's not really possible to say what the right option there is.
You should be able to do this with two different objects to represent the Contact view.
public class vwContact
{
public int KeyField { get; set; }
public string LegacyKeyField { get; set; }
}
public class vwLegacyContact
{
public int KeyField { get; set; }
public string LegacyKeyField { get; set; }
}
public class SomeObject
{
public virtual vwContact Contact { get; set; }
public int ContactId { get; set; } //references vwContact.KeyField
}
public class LegacyObject
{
public virtual vwLegacyContact Contact { get; set; }
public string ContactId { get; set; } //references vwLegacyContact.LegacyKeyField
}
ModelCreatingFunction(modelBuilder)
{
// can't set both of these, right?
modelBuilder.Entity<vwContact>().HasKey(x => x.KeyField);
modelBuilder.Entity<vwLegacyContact>().HasKey(x => x.LegacyKeyField);
// The rest of your configuration
}
I have tried everything that you can imagine, and found that most solutions won't work in this version of EF... maybe in future versions it supports referencing another entity by using an unique field, but this is not the case now. I also found two solutions that work, but they are more of a workaround than solutions.
I tried all of the following things, that didn't work:
Mapping two entities to the same table: this is not allowed in EF4.
Inheriting from a base that has no key definitions: all root classes must have keys, so that inherited classes share this common key... that is how inheritance works in EF4.
Inheriting from base class that defines all fields, including keys, and then use modelBuilder to tell wich base-properties are keys of the derived types: this doesn't work, because the methos HasKey, Property and others that take members as parameters, must reference members of the class itself... referencing properties of a base class is not allowed. This cannot be done: modelBuilder.HasKey<MyClass>(x => x.BaseKeyField)
The two things that I did that worked:
Without DB changes: Map to the table that is source of the view in question... that is, if vwContact is a view to Contacts table, then you can map a class to Contacts, and use it by setting the key to the KeyField, and another class mapping to the vwContacts view, with the key being LegacyKeyField. In the class Contacts, the LegacyKeyField must exist, and you will have to manage this manually, when using the Contacts class. Also, when using the class vwContacts you will have to manually manage the KeyField, unless it is an autoincrement field in the DB, in this case, you must remove the property from vwContacts class.
Changing DB: Create another view, just like the vwContacts, say vwContactsLegacy, and map it to a class in wich the key is the LegacyKeyField, and map vwContacts to the original view, using KeyField as the key. All limitations from the first case also applies: the vwContacts must have the LegacyKeyField, managed manually. And the vwContactsLegacy, must have the KetField if it is not autoincrement idenitity, otherwise it must not be defined.
There are some limitations:
As I said, these solutions are work-arounds... not real solutions, there are some serious implications, that may even make them undesirable:
EF does not know that you are mapping two classes to the same thing. So when you update one thing, the other one could be changed or not, it depends if the objects is cached or not. Also, you could have two objects at the same time, that represents the same thing on the backing storage, so say you load a vwContact and also a vwContactLegacy, changes both, and then try to save both... you will have to care about this yourself.
You will have to manage one of the keys manually. If you are using vwContacts class, the KeyFieldLegacy is there, and you must fill it. If you want to create a vwContacts, and associate is with a LegacyObject, then you need to create the reference manually, because LegacyObject takes a vwContactsLegacy, not a vwContacts... you will have to create the reference by setting the ContactId field.
I hope that this is more of a help than a disillusion, EF is a powerfull toy, but it is far from perfect... though I think it's going to get much better in the next versions.
I think this may be possible using extension methods, although not directly through EF as #Matthew Walton mentioned in his edit above.
However, with extension methods, you can specify what to do behind the scenes, and have a simple call to it.
public class LegacyObject
{
public virtual vwContact Contact { get; set; }
public string ContactId { get; set; } //references vwContact.LegacyKeyField
}
public class LegacyObjectExtensions
{
public static vwContact Contacts(this LegacyObject legacyObject)
{
var dbContext = new LegacyDbContext();
var contacts = from o in legacyObject
join c in dbContext.vwContact
on o.ContactId == c.LegacyKeyField
select c;
return contacts;
}
}
and
public class SomeObject
{
public virtual vwContact Contact { get; set; }
public int ContactId { get; set; } //references vwContact.KeyField
}
public class SomeObjectExtensions
{
public static vwContact Contacts(this SomeObject someObject)
{
var dbContext = new LegacyDbContext();
var contacts = from o in someObject
join c in dbContext.vwContact
on o.ContactId == c.KeyField
select c;
return contacts;
}
}
Then to use you can simply do like this:
var legacyContacts = legacyObject.Contacts();
var someContacts = someObject.Contacts();
Sometimes it makes more sense to map it from the other end of the relationship, in your case:
modelBuilder.Entity<LegacyObject>().HasRequired(x => x.Contact).WithMany().HasForeignKey(u => u.LegacyKeyField);
however this will require that u.LegacyKeyField is marked as a primary key.
And then I'll give my two cents:
if the Legacy db is using LegacyKeyField, then perhaps the legacy db will be read only. In this case we can create two separate contexts Legacy and Non-legacy and map them accordingly. This can potentially become a bit messy as you'd have to remember which object comes from which context. But then again, nothing stops you from adding the same EF code first object into 2 different contexts
Another solution is to use views with ContactId added for all other legacy tables and map them into one context. This will tax performance for the sake of having cleaner context objects, but this can be counteracted on sql side: indexed views, materialized views, stored procs, etc. So than LEGACY_OBJECT becomes VW_LEGACY OBJECT with CONTACT.ContactId brought over, then:
modelBuilder.Entity<LegacyObject>().ToTable("VW_LEGACY_OBJECT");
modelBuilder.Entity<LegacyObject>().HasRequired(x => x.Contact).WithMany().HasForeignKey(u => u.ContactId);
I personally would go with creating "mapper views" with CustomerId on legacy tables, as it's cleaner from c# layer perspective and you can make those views look like real tables. It is also difficult to suggest a solution without knowing what exactly is the scenario that you have a problem with: querying, loading, saving, etc.

Categories

Resources