简体   繁体   中英

Are there any naming conventions for multiple inverse properties in EF Core or are attributes necessary?

This article shows the following table example:

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public string Description { get; set; }

    [ForeignKey("OnlineTeacher")]
    public int? OnlineTeacherId { get; set; }
    public Teacher OnlineTeacher { get; set; }

    [ForeignKey("ClassRoomTeacher")]
    public int? ClassRoomTeacherId { get; set; }
    public Teacher ClassRoomTeacher { get; set; }
}

public class Teacher
{
    public int TeacherId { get; set; }
    public string Name { get; set; }

    [InverseProperty("OnlineTeacher")]
    public ICollection<Course> OnlineCourses { get; set; }
    [InverseProperty("ClassRoomTeacher")]
    public ICollection<Course> ClassRoomCourses { get; set; }
}

I found that I could remove the [ForeignKey(*)] attributes and they still get created on the Courses table properly. However, if I remove BOTH [InverseProperty] attributes, EF throws an error when i build. Are there naming conventions for this just like the foreign keys ? My goal is to follow the naming conventions closely and reduce the amount of attribute/fluent based configuration.

if I remove BOTH [InverseProperty] attributes, EF throws an error when i build. Are there naming conventions for this just like the foreign keys?

There is no naming convention defined by EF when many assocaitions of same type (eg 1-to-many) exit between two entities.

For example when you have one association between EntityA and EntityB . Let say it exists 1-to-* relation between EntityA and EntityB , it works well when you respect the convention. But when you put another 1-to-* relation between EntityA and EntityB , EF will need your help to know how associations are related. So you must use InverseProperty data annotation attribute or define the full relations through fluent configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM