问题
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