Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an Interface as a property with Entity Framework?

I have the following class which is a model for a database table:

public class User : IUser
{
    internal int Id { get; set; }

    public string Name { get; set; }
    public string Email { get; set; }

    public ITest TestData { get; set; }
}

When I run Update-Database command, it throws an error:

The property User.TestData is of an interface type (ITest). If it is a navigation property manually configure the relationship for this property by casting it to a mapped entity type

How and where can I manually configure the relationship for this property if I do not want the actual property to be a class?

like image 324
Elijah Dollin Avatar asked Jan 14 '18 13:01

Elijah Dollin


People also ask

Can interface contain property?

Interface can contain declarations of method, properties, indexers, and events. Interface cannot include private, protected, or internal members. All the members are public by default. Interface cannot contain fields, and auto-implemented properties.

What are the different types of properties supported in Entity Framework?

An Entity can include two types of properties: Scalar Properties and Navigation Properties. Scalar Property: The type of primitive property is called scalar properties. Each scalar property maps to a column in the database table which stores the real data.

Can we define properties in interface?

Properties in Interfaces - Yes, since they are paired methods under the hood. I believe an interface can be declared with whatever scope you want, but all exposed functionality must be at that scope.

What is the use of property in interface C#?

Interface properties typically don't have a body. The accessors indicate whether the property is read-write, read-only, or write-only. Unlike in classes and structs, declaring the accessors without a body doesn't declare an auto-implemented property.


1 Answers

EF does not support interfaces, but you can deal with it this way. Take a look on this solution How to use interface properties with CodeFirst

like image 138
Nove124 Avatar answered Oct 22 '22 11:10

Nove124