开发者

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

开发者 https://www.devze.com 2023-04-13 01:03 出处:网络
Say I have the following POCO classes: public class Parent { public int ID { get; set; } } public class Child

Say I have the following POCO classes:

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

public class Child
{
  public int ID { 开发者_如何学Pythonget; 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消