Click here to Skip to main content
15,077,377 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi guys, would it be possible to map the Image entity to the Post table and Draft table where the Image property "TypeId" becomes the foreign key to either the Post or Draft table.

Basically, A post has many images and a Draft has many images. I would like to use the "TypeId" as the foreign key so i can query using the following scenario:

"Select * from Images where TypeId = Post.Id and Type='Post'" or
"Select * from Images where TypeId = Draft.Id and Type='Draft'"

Also note that i am using EntityFrameworkCore!

 public class Post
{
    public string Id { get; private set; }
    public string Content { get; set; }
    public string UserId { get; set; }
    public DateTime Created { get; set; }
    public DateTime Edited { get; set; }
    public List<Image> Images;
}
 

public class Draft 
{
    public string IdentityGuid { get; private set; }
    public string Id { get; set; }
    public string Content { get; set; }
    public string UserId { get; set; }
    public string Title { get; set; }
    public DateTime Created { get; set; }
    public DateTime Edited { get; set; }
    public List<Image> Images;
}
    
public class Image 
{
    public string UserId { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public int TypeId { get; set; }
    public string Description { get; set; }
    public string Content_Type { get; set; }
    public string Filename { get; set; }
    public string Url { get; set; }
    public long Size { get; set; }
    public DateTime Created { get; set; }
    public DateTime Edited { get; set; }
}


What I have tried:

public void Configure(EntityTypeBuilder<Draft> draftConfiguration)
{
    draftConfiguration.HasMany(b => b.Images)
      .WithOne()
      .HasForeignKey("TypeId")
      .OnDelete(DeleteBehavior.Cascade);
}


public void Configure(EntityTypeBuilder<Post> postConfiguration)
{
    draftConfiguration.HasMany(b => b.Images)
      .WithOne()
      .HasForeignKey("TypeId")
      .OnDelete(DeleteBehavior.Cascade);
}

Posted
Updated 18-Jun-19 11:37am

1 solution

For EF to "work properly" each "entity" requires a primary key; I don't see any primary key on "Image" (or "proper" keys on the other entities for that matter).

Relationships, navigation properties and foreign keys - EF6 | Microsoft Docs[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900