Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to have "sub-models" with Entity Framework?

I was wondering if it was possible to have "sub-models" within Entity Framework entity models?

For example, this:

public class User
{
   public int Id { get; set; }

   public UserPermissions Permissions { get; set; }
}

public class UserPermissions
{
   public bool CanRead { get; set; }

   public bool CanWrite { get; set; }
}

Then in the actual table, there would be these columns:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Id
CanRead
CanWrite

or even with a prefix, like that:

Id
Perm_CanRead
Perm_CanWrite

Is that a thing? Is there an alternative you may know of? Or is my best bet to use a base/abstract class like public class User : UserPermissions { }?

>Solution :

Yes, this is possible in EF Core by using owned entities. The docs explain it pretty well but, for example, you can have this:

[Owned]
public class StreetAddress
{
    public string Street { get; set; }
    public string City { get; set; }
}

public class Order
{
    public int Id { get; set; }
    public StreetAddress ShippingAddress { get; set; }
}

Or if you prefer using the fluent API:

modelBuilder.Entity<Order>().OwnsOne(p => p.ShippingAddress);

Which will give you a table like this:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading