I'm setting my first steps in dependency injection related programming in an EntityFramework
environment, and I have following Exception
:
Database
is of the type Microsoft.EntityFrameworkCore.DatabaseFacade
.
The Database.EnsureCreated();
line gives following exception:
System.InvalidOperationException: 'No suitable constructor was found for entity type 'Element'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'ipAddress', 'strategy', 'bufferSize' in 'Element(string name, IPAddress ipAddress, short port, IStrategy strategy, short bufferSize)'; cannot bind 'ipAddress' in 'Element(IPAddress ipAddress, short port)'.'
Apparently name
and port
are well handled, but not the others. I've been looking into the constructors and the database related configuration, but I don't see how name
and port
seem to be treated better than the others. Does anybody have an idea?
The properties look as follows:
public Guid Id { get; private set; }
public string Name { get; private set; }
public ElementStatus Status { get; private set; }
public IPAddress Ip { get; }
public short Port { get; }
public short BufferSize { get; }
public IStrategy Strategy { get; }
...
The constructors look as follows:
public Element(string name, IPAddress ipAddress, short port, IStrategy Strategy, short bufferSize = 8192)
{
if (string.IsNullOrEmpty(ipAddress.ToString()))
throw new ArgumentException("Invalid IP address");
this.Name = name;
this.Ip = ipAddress;
this.Port = port;
BufferSize = bufferSize;
Strategy = Strategy;
}
public Element(IPAddress ipAddress, short port)
{
this.Ip = ipAddress;
this.Port = port;
}
The database configuration looks as follows:
public class Configurations :
IEntityTypeConfiguration<Element>
{
public void Configure(EntityTypeBuilder<Element> builder)
{
builder.Property(o => o.Id).ValueGeneratedOnAdd();
builder.Property(o => o.Name).IsRequired();
builder.HasIndex(o => o.Name).IsUnique();
builder.Property(o => o.Ip).IsRequired();
builder.Property(o => o.Port).IsRequired();
builder.Property(o => o.Status).IsRequired();
builder.HasIndex("Ip", "Port").IsUnique();
}
}
CodePudding user response:
Adding a parameterless constructor should solve this problem as this constructor is not fulfilling all required properties.
public Element(IPAddress ipAddress, short port)
{
this.Ip = ipAddress;
this.Port = port;
}
CodePudding user response:
The error message says that the constructor parameters can't be bound to the type properties. Most of the parameter names match a property name but you have a parameter named ipAddress
and a property named Ip
, so they presumably are not being mapped. If you change one or the other so they match then I think you should be OK.