0

Is there a way to use interfaces as fields of a class in EF Core (CodeFirst, last version to day 5.0)?

say

public class Order
{
   public int Id { get; set;}
   public IUser CreatedBy { get; set; }
}
Serge
  • 40,935
  • 4
  • 18
  • 45
serge
  • 13,940
  • 35
  • 121
  • 205
  • https://stackoverflow.com/questions/48250184/can-i-use-an-interface-as-a-property-with-entity-framework – Roman Ryzhiy Jan 20 '21 at 14:13
  • @RomanRyzhiy, thanks. Should it be the same for EF Core as for the EF? – serge Jan 20 '21 at 14:17
  • Not for navigation properties. With value conversions you could add an interface property to a model that is stored in a single field in the database. – Gert Arnold Jan 21 '21 at 10:17
  • `Ivan Stoev` and `Palle Due` closing as duplicate a question asking about a different framework? Event the tags show it, never mind the first sentence saying `EF Core`. – Douglas Gaskell Oct 26 '21 at 04:54

1 Answers1

3

You can use interfaces for navigation properties, that are not exist in db. But for the Db columns you need the concrete classes.

In your case you have two way :

public class Order
{
[Key]
   public int Id { get; set;}
[ForeignKey]
   public int UserId CreatedBy { get; set; }
}

This way you can save UserId to Db and reuse it. This way is prefered.

Another way :

public class Order
{
   [Key]
   public int Id { get; set;}
   [NotMapped]
   public IUser CreatedBy { get; set; }
}

But this way IUser can be used as long as an Order instance exist im memory.

Serge
  • 40,935
  • 4
  • 18
  • 45