5

Suppose I have the following entities:

public class Calendar{
    public int ID{get;set;}
    public ICollection<Day> Days { get; set; }
}
public class Day{
    public int ID{get;set;}
    public DateTime Date{get;set;}
    public int CalendarID{get;set;}
}

This is a one-to-many relationship with CalendarID as a foreign key. The issue is I also want to make sure that each date exists only once in each calendar. That is, no two days have both the same Date and same CalendarID. In raw SQL I can do this by:

ALTER TABLE Days
ADD CONSTRAINT UN_Day UNIQUE ([Date],CalendarID);

However, Entity Framework won't know I want this when it creates the table automatically. How can I specify this in the fluent API?

Matthew
  • 4,149
  • 2
  • 26
  • 53

1 Answers1

5

See Configuring an Index on one or more properties.

In your mapping class, assuming it extends from EntityTypeConfiguration<Day> then you will need to add using System.Data.Entity.Infrastructure.Annotations; and do the following:

this.Property(x => x.Date)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName,
                 new IndexAnnotation(new IndexAttribute("UN_Day", 0) { IsUnique = true }));

this.Property(x => x.CalendarID)
    .HasColumnAnnotation(IndexAnnotation.AnnotationName,
                 new IndexAnnotation(new IndexAttribute("UN_Day", 1) { IsUnique = true }));
SpruceMoose
  • 9,737
  • 4
  • 39
  • 53
  • I don't have `HasColumnAnnotation()` but I see `HasAnnotation()`. Is that a newer version of the same method? I wasn't even able to import the namespace you mentioned. Apparently, already `Entity` isn't found in `System.Data.Entity.Infrastructure.Annotations`. I checked different NuGet packages but didn't recognize anything obvious. Given that your answer is 3+ years old, I suspect that the syntax might have changed a bit. +1 anyway but I'd be delighted to get more current info too, if you have it. – Konrad Viltersten Aug 17 '21 at 05:26
  • [`HasAnnotation`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.modelbuilder.hasannotation?view=efcore-2.0) looks like the EF Core equivalent to [`HasColumnAnnotation`](https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.modelconfiguration.configuration.propertymappingconfiguration.hascolumnannotation?view=entity-framework-6.2.0) – SpruceMoose Aug 17 '21 at 07:04