I am trying to restrict a couple of generic methods to only be allowed Entities that inherit from the IParentOf<TChildEntity> interface, as well as accessing an Entity's Foreign Key (ParentId) Generically.
To demonstrate;
public void AdoptAll<TParentEntity, TChildEntity>(TParentEntity parent,
TParentEntity adoptee)
where TParentEntity : DataEntity, IParentOf<TChildEntity>
where TChildEntity : DataEntity, IChildOf<TParentEntity>
{
foreach (TChildEntity child in (IParentOf<TChildEntity>)parent.Children)
{
(IChildOf<TParentEntity)child.ParentId = adoptee.Id;
}
}
A child entity class model would look like this,
public class Account : DataEntity, IChildOf<AccountType>, IChildOf<AccountData>
{
public string Name { get; set; }
public string Balance { get; set; }
// Foreign Key and Navigation Property for AccountType
int IChildOf<AccountType>.ParentId{ get; set; }
public virtual AccountType AccountType { get; set; }
// Foreign Key and Navigation Property for AccountData
int IChildOf<AccountData>.ParentId{ get; set; }
public virtual AccountData AccountData { get; set; }
}
First of all, is this possible to do? Or will it breakdown in EF?
Secondly, since the Foreign Keys do not follow convention (and there are multiple) how do I set them via Fluent Api? I can see how to do this in Data Annotations.
I hope this is clear, I have been considering it for a while and trying to work round it, so I can follow my argument, but it may not be clearly conveyed, so please ask for clarification if needed. My reason for wanting to do this is to make the code safe as well as automating a lot of the manual changing of classes necessary to add new associations and entities.
Thanks.
Edit
I decided to create some basic classes to implement this idea and test it, my code is as follows.
public abstract class ChildEntity : DataEntity
{
public T GetParent<T>() where T : ParentEntity
{
foreach (var item in GetType().GetProperties())
{
if (item.GetValue(this) is T entity)
return entity;
}
return null;
}
}
public abstract class ParentEntity : DataEntity
{
public ICollection<T> GetChildren<T>() where T : ChildEntity
{
foreach (var item in GetType().GetProperties())
{
if (item.GetValue(this) is ICollection<T> collection)
return collection;
}
return null;
}
}
public interface IParent<TEntity> where TEntity : ChildEntity
{
ICollection<T> GetChildren<T>() where T : ChildEntity;
}
public interface IChild<TEntity> where TEntity : ParentEntity
{
int ForeignKey { get; set; }
T GetParent<T>() where T : ParentEntity;
}
public class ParentOne : ParentEntity, IParent<ChildOne>
{
public string Name { get; set; }
public decimal Amount { get; set; }
public virtual ICollection<ChildOne> ChildOnes { get; set; }
}
public class ParentTwo : ParentEntity, IParent<ChildOne>
{
public string Name { get; set; }
public decimal Value { get; set; }
public virtual ICollection<ChildOne> ChildOnes { get; set; }
}
public class ChildOne : ChildEntity, IChild<ParentOne>, IChild<ParentTwo>
{
public string Name { get; set; }
public decimal Balance { get; set; }
int IChild<ParentOne>.ForeignKey { get; set; }
public virtual ParentOne ParentOne { get; set; }
int IChild<ParentTwo>.ForeignKey { get; set; }
public virtual ParentTwo ParentTwo { get; set; }
}
Data Entity simply gives each entity an Id property.
I have standard Generic Repositories set up with a Unit of Work class for mediating. The AdoptAll method looks like this in my program.
public void AdoptAll<TParentEntity, TChildEntity>(TParentEntity parent,
TParentEntity adoptee, UoW uoW)
where TParentEntity : DataEntity, IParent<TChildEntity>
where TChildEntity : DataEntity, IChild<TParentEntity>
{
var currentParent = uoW.GetRepository<TParentEntity>().Get(parent.Id);
foreach (TChildEntity child in currentParent.GetChildren<TChildEntity>())
{
child.ForeignKey = adoptee.Id;
}
}
This seems to work correctly and without faults (minimal testing) are there any major flaws in doing this?
Thanks.
Edit Two
This is the OnModelCreating Method in the DbContext, which sets up the foreign key for each entity. Is this problematic?
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ChildOne>()
.HasOne(p => p.ParentOne)
.WithMany(c => c.ChildOnes)
.HasForeignKey(fk => ((IChild<ParentOne>)fk).ForeignKey);
modelBuilder.Entity<ChildOne>()
.HasOne(p => p.ParentTwo)
.WithMany(c => c.ChildOnes)
.HasForeignKey(fk => ((IChild<ParentTwo>)fk).ForeignKey);
}
According to the updated example, you want to hide the explicit FK from the entity class public interface, and still let it be visible to EF Core and mapped to the FK column in the database.
The first problem is that the explicitly implemented interface member is not directly discoverable by EF. Also it has no good name, so the default conventions don't apply.
For instance, w/o fluent configuration EF Core will correctly create one to many associations between Parent and Child entities, but since it won't discover the int IChild<Parent>.ForeignKey { get; set; } properties, it would maintain the FK property values through ParentOneId / ParentTwoId shadow properties and not through interface explicit properties. In other words, these properties will not be populated by EF Core and also not considered by the change tracker.
To let EF Core use them you need to map both FK property and database column name using respectively HasForeignKey and HasColumnName fluent API method overloads accepting string property name. Note that the string property name must be fully qualified with the namespace. While Type.FullName provides that string for non-generic types, there is no such property/method for generic types like IChild<ParentOne> (the result has to be "Namespace.IChild<Namespace.ParentOne>"), so let first create some helpers for that:
static string ChildForeignKeyPropertyName<TParent>() where TParent : ParentEntity
=> $"{typeof(IChild<>).Namespace}.IChild<{typeof(TParent).FullName}>.{nameof(IChild<TParent>.ForeignKey)}";
static string ChildForeignKeyColumnName<TParent>() where TParent : ParentEntity
=> $"{typeof(TParent).Name}Id";
The next would be creating a helper method for performing the necessary configuration:
static void ConfigureRelationship<TChild, TParent>(ModelBuilder modelBuilder)
where TChild : ChildEntity, IChild<TParent>
where TParent : ParentEntity, IParent<TChild>
{
var childEntity = modelBuilder.Entity<TChild>();
var foreignKeyPropertyName = ChildForeignKeyPropertyName<TParent>();
var foreignKeyColumnName = ChildForeignKeyColumnName<TParent>();
var foreignKey = childEntity.Metadata.GetForeignKeys()
.Single(fk => fk.PrincipalEntityType.ClrType == typeof(TParent));
// Configure FK column name
childEntity
.Property<int>(foreignKeyPropertyName)
.HasColumnName(foreignKeyColumnName);
// Configure FK property
childEntity
.HasOne<TParent>(foreignKey.DependentToPrincipal.Name)
.WithMany(foreignKey.PrincipalToDependent.Name)
.HasForeignKey(foreignKeyPropertyName);
}
As you can see, I'm using EF Core provided metadata services to find the names of the corresponding navigation properties.
But this generic method actually shows the limitation of this design. The generic constrains allow us to use
childEntity.Property(c => c.ForeignKey)
which compiles fine, but doesn't work at runtime. It's not only for fluent API methods, but basically any generic method involving expression trees (like LINQ to Entities query). There is no such problem when the interface property is implemented implicitly with public property.
We'll return to this limitation later. To complete the mapping, add the following to your OnModelCreating override:
ConfigureRelationship<ChildOne, ParentOne>(modelBuilder);
ConfigureRelationship<ChildOne, ParentTwo>(modelBuilder);
And now EF Core will correctly load / take into account your explicitly implemented FK properties.
Now back to limitations. There is no problem to use generic object services like your AdoptAll method or LINQ to Objects. But you can't access these properties generically in expressions used to access EF Core metadata or inside LINQ to Entities queries. In the later case you should access it through navigation property, or in both scenarios you should access in by the name returned from the ChildForeignKeyPropertyName<TParent>() method. Actually queries will work, but will be evaluated locally thus causing performance issues or unexpected behaviors.
E.g.
static IEnumerable<TChild> GetChildrenOf<TChild, TParent>(DbContext db, int parentId)
where TChild : ChildEntity, IChild<TParent>
where TParent : ParentEntity, IParent<TChild>
{
// Works, but causes client side filter evalution
return db.Set<TChild>().Where(c => c.ForeignKey == parentId);
// This correctly translates to SQL, hence server side evaluation
return db.Set<TChild>().Where(c => EF.Property<int>(c, ChildForeignKeyPropertyName<TParent>()) == parentId);
}
To recap shortly, it's possible, but use with care and make sure it's worth for the limited generic service scenarios it allows. Alternative approaches would not use interfaces, but (combination of) EF Core metadata, reflection or Func<...> / Expression<Func<..>> generic method arguments similar to Queryable extension methods.
Edit: Regarding the second question edit, fluent configuration
modelBuilder.Entity<ChildOne>()
.HasOne(p => p.ParentOne)
.WithMany(c => c.ChildOnes)
.HasForeignKey(fk => ((IChild<ParentOne>)fk).ForeignKey);
modelBuilder.Entity<ChildOne>()
.HasOne(p => p.ParentTwo)
.WithMany(c => c.ChildOnes)
.HasForeignKey(fk => ((IChild<ParentTwo>)fk).ForeignKey);
produces the following migration for ChildOne
migrationBuilder.CreateTable(
name: "ChildOne",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ForeignKey = table.Column<int>(nullable: false),
Name = table.Column<string>(nullable: true),
Balance = table.Column<decimal>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ChildOne", x => x.Id);
table.ForeignKey(
name: "FK_ChildOne_ParentOne_ForeignKey",
column: x => x.ForeignKey,
principalTable: "ParentOne",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ChildOne_ParentTwo_ForeignKey",
column: x => x.ForeignKey,
principalTable: "ParentTwo",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
Note the single ForeignKey column and the attempt to use it as foreign key to both ParentOne and ParentTwo. It suffers the same problems as using a constrained interface property directly, so I would assume it not working.
Assume I have the following entity classes:
public class Customer {
public int Id { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public class Order {
public int Id { get; set; }
public virtual Customer Customer { get; set; }
}
How should those be mapped in Entity Framework 6 fluent code-first mapping? I want to be explicit about the mapping and not rely on automatic mapping conventions.
Option 1
Just map the local properties of both classes. That's how I would do it in Fluent NHibernate.
public class CustomerMap : EntityTypeConfiguration<Customer> {
public CustomerMap() {
HasMany(x => x.Orders);
}
}
public class OrderMap : EntityTypeConfiguration<Order> {
public OrderMap() {
HasRequired(x => x.Customer);
}
}
Option 2
Map both sides of the relationship in both classes.
public class CustomerMap : EntityTypeConfiguration<Customer> {
public CustomerMap() {
HasMany(x => x.Orders).WithRequired(x => x.Customer);
}
}
public class OrderMap : EntityTypeConfiguration<Order> {
public OrderMap() {
HasRequired(x => x.Customer).WithMany(x => x.Orders);
}
}
Option 3
Map both sides of the relation, but only in one of the classes. The code would be similar to option 2, just one of the two constructors would be empty.
Is there any difference between those options? If yes, please also explain why I should or shouldn't use a specific option.
I would go for option 3.
In option 1 you can forget to map the inverse end of an association. In this simple example it's clear that Order.Customer and Customer.Orders are two ends of the same association. When things get more complex, this isn't always obvious. Also, it is redundant code.
In option 2 you could have conflicting mappings. For instance when you have...
HasOptional(x => x.Customer).WithMany(x => x.Orders);
...in OrderMap, you will get a runtime exception telling you that both mappings don't match. And again, it is redundant code.
So option 3 is DRY and safe. The only issue is that it's a bit arbitrary where to configure the mappings. I tend to adhere to mapping children in their parent's mapping.
One more comment. You may want to add a primitive property CustomerId in Order. The mapping would look like:
public class CustomerMap : EntityTypeConfiguration<Customer>
{
public CustomerMap()
{
HasMany(x => x.Orders).WithRequired(x => x.Customer)
.HasForeignKey(o => o.CustomerId);
}
}
Now you have full control over both ends of the association and the foreign key name to be used. Besides that, there are some advantages of these foreign key associations as opposed to independent associations (without a primitive foreign key property). For instance, the ability to establish an association without having to fetch the parent object from the database. You can just by set an Id value.
I'm having quite the issue trying to create a recursive relationship in Entity Framework 6.1.
I'll need some different types of Categories, but have created a "base" abstract class for all of them. I'm using Table-Per-Type hierarchical strategy. A Category may or may not have a ParentCategory. (If not, then it's a top-level category)
In the code below, I'm showing how I've created the abstract Category class and the ParentCategory and ChildCategories navigation properties. I've made the ParentCategoryId nullable, as it's not required in the case of a top-level category. I've seen a few posts that are exactly what I'm trying to achieve here, and although I've think I have all answers addressed, I'm still getting the following error:
Category_ParentCategory: : Multiplicity conflicts with the referential constraint in Role 'Category_ParentCategory_Target' in relationship 'Category_ParentCategory'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.
I'm wondering if it has something to do with Category being an abstract class and the added inheritance model I'm using as I haven't seen that exact usage in any of the other posts regarding this type of recursive relationship. Any help is appreciated!
public abstract class Category : ICategory
{
protected Category()
{
ChildCategories = new HashSet<Category>();
}
public int CategoryId { get; private set; }
public int? ParentCategoryId { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
}
public class WLCategory : Category, IWLCategory
{
public WLCategory() : base()
{
DynamicFields = new HashSet<DynamicFieldDef>();
}
public virtual ICollection<DynamicFieldDef> DynamicFields { get; set; }
}
Using FluentAPI, I've configured the database creation as such:
class CategoriesConfig : EntityTypeConfiguration<Category>
{
public CategoriesConfig()
{
HasOptional(p => p.ParentCategory).WithMany(p => p.ChildCategories)
.HasForeignKey(p => p.ParentCategoryId);
ToTable("Categories");
}
}
class WLCategoriesConfig : EntityTypeConfiguration<WLCategory>
{
public WLCategoriesConfig()
{
HasKey(p => p.CategoryId);
ToTable("WLCategories");
}
}
Ok, found the issue! In my OnModelCreating method, I had setup some global configurations, one of which was:
modelBuilder.Properties().Configure(p => p.IsRequired());
I wanted to set all properties to being non-nullable by default unless I explicitly overrode properties on a class-by-class basis. I didn't, however, think this global setting would apply to a datatype of:
int? (nullable int)
Apparently, I was wrong. (Not sure why EF would try to make a nullable int non-nullable in the DB even if the developer set IsRequired globally. The inherent meaning of int? is "nullable".) I had to explicitly add the following line of code to my CategoriesConfig class before the HasOptional statement:
Property(p => p.ParentCategoryId).IsOptional();
Now, all is well. :-)
I'm trying to implement a TPC inheritance model in EF 4.3 CodeFirst for an existing Oracle database (over which I have no control). I have several sub-types that each map to its own table. Unfortunately, some of the key columns are of datatype number(18,0) instead of integer. EF seems to hate me now.
Here's my base class:
public abstract class Vehicle
{
public virtual int Id { get; set;}
public virtual string Color { get; set; }
//more properties
}
Here are some example sub-types:
public class Car : Vehicle
{
//more properties
}
public class Truck : Vehicle
{
//more properties
}
public class Motorcycle : Vehicle
{
//more properties
}
And here's my DbContet:
public class VehicleDataContext : DbContext
{
public DbSet<Vehicle> Vehicles { get; set; }
public DbSet<Car> Cars { get; set; }
public DbSet<Truck> Trucks { get; set; }
public DbSet<Motorcycle> Motorcycles { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Vehicle>().HasKey(x => x.Id);
modelBuilder.Entity<Car>().Map(m => m.MapInheritedProperties());
modelBuilder.Entity<Car>().Property(x => x.Id).HasColumnType("decimal");
modelBuilder.Entity<Truck>().Map(m => m.MapInheritedProperties());
modelBuilder.Entity<Truck>().Property(x => x.Id).HasColumnType("int");
modelBuilder.Entity<Motorcycle>().Map(m => m.MapInheritedProperties());
modelBuilder.Entity<Motorcycle>().Property(x => x.Id).HasColumnType("decimal");
base.OnModelCreating(modelBuilder);
}
}
So, I already know to MapInheritedProperties so that all the properties of the base and sub-type are mapped to one table. I'm assuming that I have to tell the base that it HasKey so that EF doesn't complain that my DbSet<Vehicle> doesn't have a key mapped. I'd like to be able to assume that I can "tell" each entity how to map its own key's column type like I've done above. But I think that's not quite it.
Here's a test that fails:
[TestFixture]
public class when_retrieving_all_vehicles
{
[Test]
public void it_should_return_a_list_of_vehicles_regardless_of_type()
{
var dc = new VehicleDataContext();
var vehicles = dc.Vehicles.ToList(); //throws exception here
Assert.Greater(vehicles.Count, 0);
}
}
The exception thrown is:
The conceptual side property 'Id' has already been mapped to a storage
property with type 'decimal'. If the conceptual side property is
mapped to multiple properties in the storage model, make sure that all
the properties in the storage model have the same type.
As mentioned above, I have no control over the database and it's types. It's silly that the key types are mixed, but "it is what it is".
How can I get around this?
You cannot achieve it through mapping. This is limitation of EF code first. You can map each property (including the key) in inheritance structure only once. Because of that you can have it either integer or decimal in all entities in the inheritance tree but you cannot mix it.
Btw. what happens if you try to use int or decimal for the whole inheritance tree? Does it fail for loading or persisting entity? If not you can simply use the one (probably decimal if it can use whole its range) for all entities.
I'm trying to figure out what the convention would be for a value object list, in this case an IList. Here a code fragment for my domain model:
public class RegionSetting : Entity {
public virtual bool Required { get; set; }
public virtual string Name { get; set; }
public virtual IList<string> Options { get; set; }
}
My automapping is set to:
public class RegionSettingMap : IAutoMappingOverride<RegionSetting> {
public void Override(AutoMapping<RegionSetting> mapping) {
mapping
.HasMany(x => x.Options).Element("Options")
.Table("RegionSettingOptions")
.KeyColumn("RegionSettingId");
}
}
I'd like to make the .Table() and .KeyColumn() overrides into a convention so that I don't have to do that everywhere I'm using IList<string>. I thought that I could create an IHasManyConvention, but it doesn't seem to affect this mapping. I set a breakpoint in my custom HasManyConvention class, but it doesn't break for the Options property. Could anyone tell me what convention I should be using to automate this override?
Using an IHasManyConvention should've worked. Try an IBagConvention, see if that works. If not, there's a bug in there.