I want to create a table where data uniqueness is based on multiple columns (2 or 3) but one of them can be null. For example:
FRUIT WEIGHT UNIT
Apple
Apple 1 Kg
Apple 2 Kg
Orange
Orange 1 Kg
Orange 2 Kg
will all be considered as unique entries. Can it be done with EF 6.1 Data Annotations? I beleive I achieved that like this:
[Required]
[Index("UniqueIndx", 1)]
public string Name { get; set; }
[Index("UniqueIndx", 2)]
public float? Weight { get; set; }
[Index("UniqueIndx", 3, IsUnique = true)]
public FormulUnit? Unit { get; set; }
which produces:
public override void Up()
{
AlterColumn("MyDb.Fruits", "Weight", c => c.Single());
AlterColumn("MyDb.Fruits", "Unit", c => c.Int());
CreateIndex("MyDb.Fruits", new[] { "Name", "Weight", "Unit" },
unique: true, name: "UniqueIndx");
}
From my understanding of Up method created by migration is that uniqueness is based on all 3 columns, not just last one I wrote that annotation to. This is ok for me, this is actually what I want.
I still have the problem of seeding that table. I'm getting errors on AddOrUpdate method like:
System.InvalidOperationException: The binary operator Equal is not defined for the types 'System.Nullable`1[System.Single]' and 'System.Single'.
for:
context.Fruits.AddOrUpdate(
p => new {p.Name, p.Weight, p.Unit}, fr1, fr2, fr3
);
Am I missing something? Thanks