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; }
}
6
  • I'm not sure I understand your question. A navigation property is a virtual property of reference type. Commented Sep 1, 2017 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 Commented Sep 1, 2017 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: learn.microsoft.com/en-us/dotnet/framework/data/adonet/… Commented Sep 1, 2017 at 11:52
  • @AkosNagy, thanks. I changed the description Commented Sep 1, 2017 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? Commented Sep 1, 2017 at 12:09

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

-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; }
}

6 Comments

It seems you missed the part where OP wrote no virtual properties of reference type
Thanks for your response, but models shouldn't be changed and definition should be done by Fluent API
Whoops.. sorry :)
May I ask why you don't want them to be virtual @AlexZaitsev?
@AlexZaitsev The fact that the property is virtual is not equal to informing the models about the existence of EF. If you were using annotations then I'd agree with you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.