Question
This Content is from Stack Overflow. Question asked by Osama Ahmed
I have entity called activity contains 2 list of models will be saved as json on db
i faced exception when i get entity say that :
[ERR] The entity type 'LicenseModel' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.
System.InvalidOperationException: The entity type 'LicenseModel' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.
so licenseModel is not configured as entity it’s column why he see as entity.
i figure that DateTime Properties in LicenseModel make this issue happend, when i change type to DateOnly or DateTimeOffset the issue not happend.
i used entity framework core version 6.0.7
i can use [Keyless] attibute on model or configure model in dbcontext
like this builder.Entity().HasNoKey(); but i need to
know why he see model as entity.
Entity Configuration
public class ActivitiesConfiguration : IEntityTypeConfiguration<Activities>
{
public void Configure(EntityTypeBuilder<Activities> builder)
{
builder.ToTable(nameof(Activities), DbSchema).HasKey(b => b.RequestId);
builder.ConfigureByConvention();
builder.Property(x => x.RequestId).IsRequired();
builder.Property(x => x.Licenses).HasConversion(x => x.ToJSON(), x => x.ToModel<List<LicenseModel>>());
}
}
Entity
public class Activities : AuditedEntityTimeWithoutId
{
public Guid RequestId { get; private set; }
public List<LicenseModel> Licenses { get; private set; }
}
Model
public class LicenseModel
{
public string LicenseNumber { get; private set; }
public DateTime IssueDate { get; private set; }
public DateTime ExpireDate { get; private set; }
}
Thanks For Support.
Solution
This exception message doesn’t mean it requires a primary key to be defined in your database, it means it requires a primary key to be defined in your class.
Although you’ve attempted to do so:
private Guid _id;
[Key]
public Guid ID
{
get { return _id; }
}
This has no effect, as Entity Framework ignores read-only properties. It has to: when it retrieves a Fruits
record from the database, it constructs a Fruit
object, and then calls the property setters for each mapped property. That’s never going to work for read-only properties.
You need Entity Framework to be able to set the value of ID
. This means the property needs to have a setter.
Answered by user743382
This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 4.0.