One-to-one and one-to-many relationships with same owned entity type

≡放荡痞女 提交于 2020-06-29 04:14:31

问题


After this question I tried working with owned entity types but I'm stuck at the following scenario:

public class User
{
    [Key]
    public Guid UserId { get; set; }
    public ICollection<Listing> Listings { get; set; }
    public Image Avatar { get; set; }
}

public class Listing
{
    [Key]
    public Guid ListingId { get; set; }
    public ICollection<Image> Photos { get; set; }
}

[Owned]
public class Image
{
    public long Size { get; set; }
    public string Height { get; set; }
    public string Width { get; set; }
}

public class DataContext : DbContext
{
    public DataContext(DbContextOptions<DataContext> options) : base(options) { }

    public DbSet<User> Users { get; set; }
    public DbSet<Listing> Listings { get; set; }    
}

But when creating the first migration I got the following error:

The entity type 'Listing.Photos#Image' requires a primary key to be defined.

So I did just that and got another error:

[Owned]
public class Image
{
    [Key]
    public Guid ImageId { get; set; }
    public long Size { get; set; }
    public string Height { get; set; }
    public string Width { get; set; }
}

Cannot use table 'Users' for entity type 'User.Avatar#Image' since it is being used for entity type 'User' and there is no relationship between their primary keys.

The only way I managed to workaround this was to create a duplicate of Image called Photo with an PhotoId and the migration was created successfully but that it's not what I'm supposed to do, I hope.

来源:https://stackoverflow.com/questions/60104976/one-to-one-and-one-to-many-relationships-with-same-owned-entity-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!