How do you map subclass properties to columns in Table per Hierarchy? - entity-framework

I have a TPH situation where I have an abstract base class and 8 derived classes from it by using a discriminator. Two of them share a list of sub classes.
public abstract class StepBase : FullAuditedEntity<Guid>
{
public int Order { get; set; }
public StepType StepType { get; set; }
}
The thing is I have two types which shares a SubClass
public class DestinationVesselStep : StepBase
{
public virtual List<DestinationVessel> VesselsDestination { get; set; }
}
public class LiquidNitrogenStep : StepBase
{
public virtual List<DestinationVessel> DestinationsBoxes { get; set; }
}
private static void ConfigureVesselsStep(ModelBuilder builder)
{
builder.Entity<DestinationVesselStep>(b =>
{
//Properties
b.HasMany(p => p.VesselsDestination).WithOne().HasForeignKey(x => x.StepId);
});
}
private static void ConfigureLiquidNitrogenStep(ModelBuilder builder)
{
builder.Entity<LiquidNitrogenStep>(b =>
{
//Properties
b.HasMany(p => p.DestinationsBoxes).WithOne().HasForeignKey(x => x.StepId);
});
}
But when I request a LiquidNitrogenStep with two or more destinationBoxes I get the following error:
System.InvalidOperationException : Sequence contains more than one element.
it works fine if I only have one destinationBox
I am expecting to get a LiquidNitrogenStep with all its destination boxes, the error do not happnd with DestinationVesselStep

DestinationVessel.StepId can't refer to both a DestinationVesselStep and LiquidNitrogenStep.
So either add separate foreign keys to DestinationVessel, eg LiquidNitrogenStepId, and DestinationVesselStepId, or make the relationships many-to-many, which uses separate linking tables for each relationship, instead of putting foreign keys on the target Entity.
private static void ConfigureVesselsStep(ModelBuilder builder)
{
builder.Entity<DestinationVesselStep>(b =>
{
//Properties
b.HasMany(p => p.VesselsDestination).WithMany( d => d.DestinationSteps);
});
}
private static void ConfigureLiquidNitrogenStep(ModelBuilder builder)
{
builder.Entity<LiquidNitrogenStep>(b =>
{
//Properties
b.HasMany(p => p.DestinationsBoxes).WithMany(d => d.LiquidNitrogenSteps);
});
}

Related

How to map in EF Core 6 a value object with derive classes?

I have an Order and an OrderState class, but I will implement state pattern, so I will have a base class State and derived classes for each state.
The classes would be this:
class Order
{
long Id;
Status State;
}
class Status
{
string abstract State;
public abstract void Method1();
}
class Status1 : Status
{
public Status1()
{
State = "Status1";
public ovderride Method1()
{
//do something
}
}
string override State;
}
class Status2 : Status
{
public Status1()
{
State = "Status2";
}
string override State;
public override void Method1()
{
// do something
}
}
In EF Core, I have a class to configure Order with Fluent API:
paramPedidoCompraConfiguracion
.OwnsOne(miOrder => miOrder.State, stateNavigationBuilder =>
{
sateNavigationBuilder.WithOwner();
stateNavigationBuilder.Property<string>(x => x.State)
.HasColumnName("State")
.HasColumnType("varchar(200)")
.IsRequired()
.IsUnicode(false)
.HasMaxLength(200);
});
}
But I get this error:
The corresponding CLR type for entity type 'Status' cannot be instantiated, and there is no derived entity type in the model that corresponds to a concrete CLR type.
I have read the documentation about this in Microsoft docs: https://learn.microsoft.com/en-us/ef/core/modeling/inheritance, in particular in the shared columns, because I want to share the column to avoid to have one column for each state.
This is the code in the documentation:
public class MyContext : DbContext
{
public DbSet<BlogBase> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.HasColumnName("Url");
modelBuilder.Entity<RssBlog>()
.Property(b => b.Url)
.HasColumnName("Url");
}
}
public abstract class BlogBase
{
public int BlogId { get; set; }
}
public class Blog : BlogBase
{
public string Url { get; set; }
}
public class RssBlog : BlogBase
{
public string Url { get; set; }
}
It is defining a dbSet for the base blog, but in my case I am using the state as value object, not as identity, so if I am not wrong, I shouldn't to create a dbSet for values objects, only for entities. So if it is correct, I don't know how to configure my value object with derived classes.
How could I do it?
Thanks.

Entity Framework Core 5.0.3 - One To One mapping with shadow property foreign keys

For the life of me, I cannot get this to work properly. I have a relatively simple domain model that has a couple of navigation properties that I want to fill out via eager loading.
To keep my domain model pure, I have opted to use shadow properties as foreign keys, so they are not accessible by the client code.
This is the domain model:
public class CourseType : Entity
{
protected CourseType() { }
public CourseType(string name, CoachGroup coachGroup, bool active)
{
Name = name;
CoachGroup = coachGroup;
Active = active;
}
public string Name { get; private set; }
private int? _coachGroupId;
private int? CoachGroupId => _coachGroupId;
public virtual CoachGroup CoachGroup { get; private set; }
public int? AgeLimit { get; private set; }
public bool Active { get; private set; }
public bool ShowInSearchForm { get; private set; }
private List<Course> _accessGivingCourses = new List<Course>();
public virtual IReadOnlyList<Course> AccessGivingCourses => _accessGivingCourses?.ToList();
}
This is how I wire the configuration up:
public class CourseTypeConfiguration : IEntityTypeConfiguration<CourseType>
{
public void Configure(EntityTypeBuilder<CourseType> builder)
{
builder.ToTable("CourseTypes", "Courses");
builder.HasKey(p => p.Id);
builder.Property(p => p.Id).HasColumnName("CourseTypeId");
builder.Property(p => p.Name).HasColumnName("CourseTypeName");
builder.Property(p => p.Active).HasColumnName("IsActive");
builder.Property(p => p.ShowInSearchForm).HasColumnName("ShowInSearchForm");
builder.Property(p => p.AgeLimit).HasColumnName("AgeLimit");
builder.Property<int?>("CoachGroupId").HasField("_coachGroupId");
builder.HasOne(p => p.CoachGroup).WithOne().HasForeignKey<CourseType>("CoachGroupId").OnDelete(DeleteBehavior.Restrict);
builder.HasMany(p => p.AccessGivingCourses).WithMany("AccessGivingCourses")
.UsingEntity<Dictionary<string, object>>("CourseTypesAccessGivingCourses",
j => j.HasOne<Course>().WithMany().HasForeignKey("CourseId"),
j => j.HasOne<CourseType>().WithMany().HasForeignKey("CourseTypeId"),
j => j.ToTable("CourseTypesAccessGivingCourses")
);
builder.HasIndex("CoachGroupId").IsUnique(false);
}
}
This is how I extract the data via my repository class:
public override async Task<IEnumerable<CourseType>> GetAll()
{
try
{
return await Context.CourseTypes.Include(i => i.CoachGroup).Include(i => i.AccessGivingCourses).ToListAsync();
}
catch (Exception e)
{
Logger.LogCritical(e, $"Could not retrieve list of course type entities");
throw;
}
}
It ALMOST works, except for the fact that when I add or update entities, the CoachGroup link randomly gets lost for some updates. For others, it works just fine. It's like Entity Framework Core OR the database randomly loses track of it. Which is odd, because when I look in the database table, the foreign keys in the table are all there like they're supposed to!?
Does anyone have any idea what the hell I am doing wrong? Or if this is the correct approach to this problem at all? All I want to do is to load related data, but it's getting to the point where it's becoming rocket science to merely link a couple of optional relationships together...

Property not being ignored in EntityTypeConfiguration?

I have a simple entity class with a list of base classes, which is ignored in the model:
public class MyClass
{
public int Id {get;set;}
public List<BaseChild> BaseChildren {get; set;}
}
Which has this configuration:
public class MyClassConfiguration : IEntityTypeConfiguration<MyClass>
{
public void Configure(EntityTypeBuilder<MyClass> builder)
{
builder.Property(o => o.Id).UseHiLo();
builder.HasKey(o => o.Id);
builder.Ignore(o => o.BaseChildren);
}
}
I have classes that inherit from BaseChild and they all use this configuration:
public abstract class BaseChild
{
public int MyClassId { get; set; }
}
public abstract class BaseChildConfiguration<T> : IEntityTypeConfiguration<T> where T : BaseChild
{
public virtual void Configure(EntityTypeBuilder<T> builder)
{
builder.HasKey(o => o.MyClassId);
builder.HasOne<MyClass>()
.WithOne()
.HasForeignKey<T>(o => o.MyClassId);
}
}
public class Instance : Component
{
public long Code { get; set; }
}
public class InstanceConfiguration : BaseChildConfiguration<Instance>
{
}
All the configurations are properly being applied in my OnModelCreating:
protected override void OnModelCreating(ModelBuilder mb)
{
mb.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
Yet for some reason I keep getting the following exception:
A key cannot be configured on 'Instance' because it is a derived type. The key must be configured on the root type 'BaseChild'. If you did not intend for 'BaseChild' to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model.

Using DTO with OData in .NetCore 2.1

I am writing a test OData Rest API with an InMemoryDatabase.
I would like to use DTO(s) to hide the SQL model and adjust a few fields (geographic positions and so on).
However, when I use ProjectTo<...> method from AutoMapper, GET request to the API return an empty collection instead of the actual result list.
Do you have any idea about what I am doing wrong ?
Here is the controller :
namespace offers_api.Controllers
{
public class OffersController : ODataController
{
private readonly OfferContext _context;
private IMapper _mapper;
public OffersController(OfferContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
[EnableQuery]
public IActionResult Get()
{
IQueryable<Offer> res = _context.Offers.ProjectTo<Offer>(_mapper.ConfigurationProvider); // <-- works without ProjectTo !
return Ok(res);
}
}
}
The automapper declaration :
namespace offers_api.Entities
{
public class Mapping : Profile
{
public Mapping()
{
//CreateMap<CategoryEntity, string>().ConvertUsing(cat => cat.Name ?? string.Empty);
CreateMap<LocationEntity, Location>()
.ForMember(x => x.longitude, opt => opt.MapFrom(o => 0))
.ForMember(x => x.latitude, opt => opt.MapFrom(o => 0))
.ReverseMap();
CreateMap<OfferEntity, Offer>()
.ForMember(x => x.Category, opt => opt.MapFrom(o => o.Category.Name))
.ReverseMap()
.ForMember(x => x.Category, opt => opt.MapFrom(o => new CategoryEntity { Name = o.Category }));
CreateMap<OfferPictureEntity, OfferPicture>().ReverseMap();
CreateMap<UserEntity, User>().ReverseMap();
}
}
}
The EDM model :
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Offer>("Offers");
return builder.GetEdmModel();
}
I found the solution.
In fact, automapper loaded more data than OData's default behaviour.
The relation between an offer and it's author was described by a non nullable foreing key. I didn't insert any author in the DB, but OData tried to load a user and saw it was missing in the USER table, so it discarded the Offer result.
Solution : make the foreign key nullable.
namespace offers_api.Entities
{
public class OfferEntity
{
[Key]
public long Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public long AuthorId { get; set; } // <== Bug here : add long? to resolve it...
public virtual UserEntity Author { get; set; }
}
}

EF5 Code first TPH Mapping error using DBSet.Find()

When using Entity Framework 5 Code First, with Table Per Hierarchy.
This combined with a Repository and Unit of Work (tried several implementations).
I'm having the following error:
(34,10) : error 3032: Problem in mapping fragments starting at lines 19, 34:EntityTypes T, T are being mapped to the same rows in table T. Mapping conditions can be used to distinguish the rows that these types are mapped to.
I have resolved this issue using the following guide:
Entity Framework 4.3 - TPH mapping and migration error
This works when using a general look-up of all records, then no errors.
When using the DBSet<T>.Find(id), I receive the above error message.
When using DBSet<T>.Where(t => t.id == id) all works fine.
Please does anyone have the solution for this problem?
public class TDataContext : DbContext
{
// Models
public abstract class BaseTrackable
{
public DateTime DateModified { get; set; }
}
public abstract class ParentClass : BaseTrackable
{
public int ParentId { get; set; }
public string ParentString { get; set; }
}
public class Foo : ParentClass
{
public string FooString { get; set; }
}
public class Bar : ParentClass
{
public string BarString { get; set; }
}
// Configuration
public class ParentConfiguration : EntityTypeConfiguration<ParentClass>
{
public ParentConfiguration()
{
ToTable("Parent");
}
}
public class FooConfiguration : EntityTypeConfiguration<Foo>
{
public FooConfiguration()
{
Map(m => m.Requires("FooIndicator").HasValue(true));
}
}
public class BarConfiguration : EntityTypeConfiguration<Bar>
{
public BarConfiguration()
{
Map(m => m.Requires("BarIndicator").HasValue(true));
}
}
public DbSet<ParentClass> Parent { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations
.Add(new ParentConfiguration())
.Add(new FooConfiguration())
.Add(new BarConfiguration());
}
}
public class Controller
{
TDataContext _context = new TDataContext();
// Repository function
public T GetById<T>(object id) where T : class
{
var dbset = _context.Set<T>();
return dbset.Find(id);
}
public IQueryable<TDataContext.Foo> GetFiltered(Expression<Func<TDataContext.Foo, bool>> filter)
{
var dbset = _context.Set<TDataContext.Foo>();
return dbset.Where(filter);
}
// Final call
// Which fails..
public TDataContext.Foo Get(int id)
{
return this.GetById<TDataContext.Foo>(id);
}
// This works...
public TDataContext.Foo GetWhere(int id)
{
return this.GetFiltered(f => f.ParentId == id).FirstOrDefault();
}
}
Found something that solves my problem partially...
When adding another indicator to the tables, there is no more error, example:
public class FooConfiguration : EntityTypeConfiguration<Foo>
{
public FooConfiguration()
{
Map(m => {
m.Requires("FooIndicator").HasValue(true);
m.Requires("BarIndicator").HasValue<short>(1);
});
}
}
public class BarConfiguration : EntityTypeConfiguration<Bar>
{
public BarConfiguration()
{
Map(m => {
m.Requires("BarIndicator").HasValue(true);
m.Requires("FooIndicator").HasValue<short>(0);
});
}
}
Wouldn't be better
public class FooConfiguration : EntityTypeConfiguration<Foo>
{
public FooConfiguration()
{
Map(m => m.Requires("Type").HasValue("Foo"));
}
}
public class BarConfiguration : EntityTypeConfiguration<Bar>
{
public BarConfiguration()
{
Map(m => m.Requires("Type").HasValue("Bar");
}
}
In this way FooConfiguration doesn't need to know anything about BarConfiguration and visa versa. I had this issue when migrating from EF 4.3 to 5.0 and I think what has changed was the discriminator database columns are not nullable in EF 5.0. I think it makes much more sense for them to be not nullable and in general it might be better to have only one discrimanotor column for each derived type as opposed to one column per type (as it was in EF 4.3)
-Stan