DMac the Destroyer
DMac the Destroyer

Reputation: 5290

EF Code First unidirectional One-To-Many with Data Annotations

Say I have the following POCO classes:

public class Parent
{
  public int ID { get; set; }
}

public class Child
{
  public int ID { get; set; }

  public int MyParentID { get; set; }

  [ForeignKey("MyParentID")]
  public Parent MyParent { get; set; }
}

The Child.MyParent property maps to the Parent table with a one-to-many relationship, but I don't want the Parent class to be aware of the association (unidirectional). I can do this within the DbContext.OnModelCreating (or any of its equivalents) with the following:

modelBuilder.Entity<Child>()
  .HasRequired(c => c.MyParent)
  .WithMany()
  .HasForeignKey(c => c.MyParentID);

But, I can't seem to find the same with data annotations. Is there such a thing? The ForeignKey annotation I am using seems to require bidirectionality, because it gives me the "Unable to determine the principal end of an association" exception until I add an ICollection<Child> property on the Parent class

UPDATE This code should actually work as-is. The issue I was trying to isolate in my code didn't actually involve this setup. I've posted a new question regarding my problem here.

Upvotes: 1

Views: 2806

Answers (1)

Slauma
Slauma

Reputation: 177163

public class Child
{
    public int ID { get; set; }
    [ForeignKey("Parent")]
    public int ParentID { get; set; }
    public Parent Parent { get; set; }
}

should work. Actually you don't need to do anything - neither in Fluent API nor with annotations - because EF conventions will exactly create the relationship automatically you have defined in Fluent API. The foreign key will be detected because it has the name pattern [Navigation property]Id, the relationship will be "required" because the FK is non-nullable and it will be one-to-many because you have a single reference (Parent) on one side and "many" on the other side is default if there is no corresponding navigation property.

Upvotes: 2

Related Questions