0

I have a code first application which defined like this:

public abstract class Entity
{
    [Key]
    public int Id { get; set; }

    public DateTime CreatedOn { get; set; }
}

public class Post : Entity
{
    public string Text { get; set; }
    public virtual ICollection<UserObject> Likes { get; set; }
} 

public class Blog : Post
{
    public string Title { get; set; }
    public string Content { get; set; }
}

public class Comment : Post
{
    public string Content { get; set; }
    public virtual Post Parent { get; set; }
}

public class UserObject : Entity
{
    public string Username { get; set; }
    public string Login { get; set; }
}

public class Profile : UserObject
{
    public DateTime DoB { get; set; }
    public string Avatar { get; set; }
    public ICollection<Blog> Blogs { get; set; } 
}

The idea is: A profile can have many blogs, a post (blog or comment) can have many likes. I want something like this on database:

Table Posts

Id
...

Table Profiles

Id
...

Table PostLikes

Id
PostId
UserId

Table ProfileBlogs

Id
UserId
BlogId

I tried but can't get Fluent API to generate these schemes. I tried with many-to-many relations, but because my data structure has inheritances, so it does not work.

How to do this in Fluent API?

Charles
  • 50,943
  • 13
  • 104
  • 142
Delta76
  • 13,931
  • 30
  • 95
  • 128

1 Answers1

1

Here's a schema that worked for me:

The fluent mapping:

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Profile>()
                .Map(m => m.ToTable("Profiles"));

            modelBuilder.Entity<Post>()
                .HasMany(p => p.Likes)
                .WithMany()
                .Map(m =>
                    {
                        m.ToTable("PostLikes");
                        m.MapLeftKey("PostId");
                        m.MapRightKey("UserId");
                    });

            modelBuilder.Entity<Profile>()
                .HasMany(p => p.Blogs)
                .WithMany()
                .Map(m =>
                {
                    m.ToTable("ProfileBlogs");
                    m.MapLeftKey("UserId");
                    m.MapRightKey("BlogId");
                });
        }

Created this database:

enter image description here

Mark Oreta
  • 10,346
  • 1
  • 33
  • 36
  • Hi, thanks for that. But the reason I created the UserObject was load the "full" Profile is sometimes overkill, especially UserObjects are used extensively – Delta76 Sep 12 '12 at 14:52
  • I've updated the answer to have a user object table, so you can create either entity – Mark Oreta Sep 12 '12 at 14:56