I have a data model where I am connecting to the same table 3 times. I can do this in SQL by using aliases, but I am unsure if it is possible to do this in ASP.NET Core 7 MVC with Entity Framework. Are you able to "alias" a model and have the same model in a view 3 times?
You could try as below:
Create two Entity
public class EntityA
{
public int Id { get; set; }
public string? PropA { get; set; }
public int ETB1Id { get; set; }
public EntityB ETB1 { get; set; } = default!;
public int ETB2Id { get; set; }
public EntityB ETB2 { get; set; } = default!;
public int ETB3Id { get; set; }
public EntityB ETB3 { get; set; } = default!;
}
public class EntityB
{
public int Id { get; set; }
public string? PropB { get; set; }
}
DbContext:
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet EntityA> EntityA { get; set; } = default!;
public DbSet< EntityB> EntityB { get; set; } = default!;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// I tried with one to one relationship,it also works for one to many relationship
modelBuilder.Entity<EntityA>().HasOne(x => x.ETB1).WithOne().OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<EntityA>().HasOne(x => x.ETB2).WithOne().OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<EntityA>().HasOne(x => x.ETB3).WithOne().OnDelete(DeleteBehavior.Restrict);
}
}
load related data in controller:
var targetitems = _context.EntityA.Include(x => x.ETB1).Include(x => x.ETB2).Include(x => x.ETB3).ToList();
Succeeded: