4

Is any way of defining Entity Framework relations using foreign keys only (no virtual properties of reference type) with FluentAPI (data models should not be changed)?

CardDataModel

public class CardDataModel
{
    public int CardId { get; set; }

}

CheckItemDataModel

public class CheckItemDataModel
{
    public int CheckItemId { get; set; }
    public int CardId { get; set; }
}
Alex Zaitsev
  • 2,544
  • 5
  • 18
  • 27
  • I'm not sure I understand your question. A navigation property *is* a virtual property of reference type. – Akos Nagy Sep 01 '17 at 11:39
  • Akos Nagy, no. A navigation property is CardId in CheckItemDataModel. Models shouldn't be changed. Definition should be done by FluentAPI only – Alex Zaitsev Sep 01 '17 at 11:42
  • CardId is called a *foreign key property*. A navigation property is by definition a property that holds a reference to the other of the association. Here's a more detailed description: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/navigation-property – Akos Nagy Sep 01 '17 at 11:52
  • @AkosNagy, thanks. I changed the description – Alex Zaitsev Sep 01 '17 at 12:05
  • 1
    Can I ask why do you want this? What are the advantages of having a model class/object without Navigation properties? – AndrasCsanyi Sep 01 '17 at 12:09
  • You cannot define a relationship without a navigation property. The navigation property *is* the relationship. If you only have the foreign key property, then you always have to explicit query for the related objet yourself, you have no relationship fixup (because you don't have a realtionship) etc. The only thing you can do is map the foreign key property to an actual foreign key in the database with migrations, but you can set that up manually as well in the db, without affecting the model. – Akos Nagy Sep 01 '17 at 12:15

2 Answers2

9

Yes, it's possible in EF Core. It wasn't in EF6 and below, but now EF Core provides parameterless overloads of HasMany / HasOne which allow configuring such relationship:

modelBuilder.Entity<CardDataModel>()
    .HasMany<CheckItemDataModel>() // <-- note this
    .WithOne()
    .HasForeignKey(e => e.CardId);
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
-2

You could do this.

public class Card
{
    public int Id { get; set; }
}

public class CheckItem
{
    public int Id { get; set; }
    public int CardId { get; set; }
    public virtual Card Card { get; set; }
}
Maritim
  • 2,111
  • 4
  • 29
  • 59