3

I'm trying to do a one-to-many relationship in Entity Framework where one of the many items is optionally designated as default.

public class SomeEntity
{
    public int Id { get; set; }
    public Item DefaultItem { get; set; }          // Optional
    public ICollection<Item> Items { get; set; }
}

public class Item
{
    public int Id { get; set; }
    public string ItemName { get; set; }
    public SomeEntity SomeEntity { get; set; }
}

The configuration for the one-to-many in fluent API seems pretty straightforward:

HasMany(e => e.Items).WithRequired(i => i.SomeEntity).WillCascadeOnDelete(true);

But the solution for implementing the default item has proven elusive. I tried this (and various variations) with no luck. It tells me that 'Schema specified is not valid'.

HasOptional(e => e.DefaultItem).WithRequired(i => i.SomeEntity);

Any ideas? Thanks in advance.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
RogerMKE
  • 667
  • 4
  • 12
  • http://stackoverflow.com/questions/12458887/entity-framework-fluent-api-to-map-simple-one-to-many-relation – hackp0int Apr 01 '13 at 21:47

1 Answers1

3

That is a bit untypical 'setup' (and it's usually designated via some 'flag' on the item - but I can possibly see a need for something similar), and relating one item to the same parent twice.

However, this should work...

modelBuilder.Entity<SomeEntity>()
    .HasOptional(x => x.DefaultItem)
    .WithOptionalPrincipal() // x => x.DefaultForEntity)
    .WillCascadeOnDelete(false);
...
// public SomeEntity DefaultForEntity { get; set; } // optional

...and use it like:

var item = new Item { ItemName = "Default1", };
db.SomeEntities.Add(new SomeEntity { DefaultItem = item, Items = new[]
{
    item,
    new Item{ ItemName = "Item1", },
    new Item{ ItemName = "Item2", },
    new Item{ ItemName = "Item3", },
    new Item{ ItemName = "Item4", },
}
});
db.SaveChanges();
NSGaga-mostly-inactive
  • 14,052
  • 3
  • 41
  • 51
  • That did the trick. Thanks so much! The reason I didn't use a flag is because that would allow the possibility of two records have their flags set. Having a single field that holds the Id of the default item ensures that there is no possibility of any errors in the data. – RogerMKE Apr 02 '13 at 01:14