Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
EF6 - TPH foreign key mapping in derived classes not working
namespace ConsoleApplication1
{
using System.Data.Entity;
class Program
{
static void Main()
{
using (var db = new Context())
{
db.Database.Delete();
db.Database.Initialize(false);
}
}
}
public class User
{
public int Id { get; set; }
}
public class Movie
{
public int Id { get; set; }
}
public abstract class Tag
{
public int Id { get; set; }
}
public class UserTag : Tag
{
public int UserId { get; set; }
public virtual User User { get; set; }
}
public class MovieTag : Tag
{
public int MovieId { get; set; }
public virtual Movie Movie { get; set; }
}
public class Context : DbContext
{
public DbSet<Tag> Tags { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Tag>()
.Map<UserTag>(m => m.Requires("TagType").HasValue("usertag"))
.Map<MovieTag>(m => m.Requires("TagType").HasValue("movietag"));
modelBuilder.Entity<UserTag>()
.Property(m => m.UserId).HasColumnName("ItemId");
modelBuilder.Entity<UserTag>()
.HasRequired(m => m.User).WithMany().HasForeignKey(m => m.UserId);
modelBuilder.Entity<MovieTag>()
.Property(m => m.MovieId).HasColumnName("ItemId");
modelBuilder.Entity<MovieTag>()
.HasRequired(m => m.Movie).WithMany().HasForeignKey(m => m.MovieId);
}
}
}
@nitinjs

This comment has been minimized.

Copy link

@nitinjs nitinjs commented Apr 25, 2019

so did you found any solution for this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.