简体   繁体   中英

Entity Framework fluent mapping foreign key

I have these entity classes (simplified):

public class MyClass 
{
      int Id {get;set;}
      int MyObjectId {get;set;}
      MyObject MyObject {get;set;}
}

public class MyObject 
{
      int Id {get;set;}
      string Name {get;set;}
      ICollection<MyClass> MyClass {get;set;}
}

Fluent mapping

HasRequired(x => x.MyObject).WithMany(x => x.MyClass)
    .HasForeignKey(x => x.MyObjectId).WillCascadeOnDelete(false);

I am just starting to learn EF, so I have two questions

Can I avoid using MyObjectId to tell EF how to map things or should I get rid of MyObject class inside MyClass and use MyObjectId instead, and whenever I need that nested data from table I should pull it by MyObjectId? As at this point it doesn't feel right to have both.

Fluent api requires me to have reference to MyClass in MyObject just to specify WithMany property, I actually don't need access to MyClass from MyObject - any guidance?

I guess I am used to nHibernate...

See the documentation here:

Entity Framework fluent mapping foreign key

See the section "Renaming a Foreign Key That Is Not Defined in the Model"

BTW long ago I tried defining my models with navigation properties only (no FK). I don't remember exactly why I gave up on that but I ran into problems and wound up putting FK's on all my entities. That is just my experience others may tell you differently.

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