This is my entity class :
public class TenantUsageLog
{
[Key]
public Guid Id { get; set; }
public Tenant Tenant { get; set; }
[DataType(DataType.Date)]
public DateTime LogDate { get; set; }
public int DatabaseRowCount { get; set; }
public int DailyTraffic { get; set; }
}
I want to create a unique constraint with Tenant object and LogDate
I am adding this code on ApplicationDbContext>OnModelCreating :
builder.Entity<TenantUsageLog>().HasIndex(p => new { p.Tenant.Id, p.LogDate }).IsUnique();
It returns this error during add-migration :
The properties expression 'p => new <>f__AnonymousType5`2(Id = p.Tenant.Id, LogDate = p.LogDate)' is not valid. The expression should represent a simple property access: 't => t.MyProperty'. When specifying multiple properties use an anonymous type: 't => new { t.MyProperty1, t.MyProperty2 }'. (Parameter 'propertyAccessExpression')
I have also tried this :
builder.Entity<TenantUsageLog>().HasIndex(p => new { p.Tenant, p.LogDate }).IsUnique();
This time,it returns with this error :
The property 'TenantUsageLog.Tenant' is of type 'Tenant' which is not supported by current database provider. Either change the property CLR type or ignore the property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
So,could you please help me to handle this problem ? I want to create a unique constraint which helps me to not add same data contains Tenant.Id and LogDate.
Thanks.
HasIndexthat accepts string array as property names. You can use that overload and you may specify shadow properties. It should work on later versions of EF core but not so sure about 3.1. You can give it a try.