Home > Software design >  Creating objects in ASP.NET Core 6 with EF Core, when they contain foreign keys
Creating objects in ASP.NET Core 6 with EF Core, when they contain foreign keys

Time:05-23

I'm a beginner with .NET and I'm having a hard time understanding how to create objects with foreign keys.

Let's say I have this Localitate entity (which vaguely translates to city) which contains a FK to Judet (county):

namespace xx.DataLayer.Entities
{
    public class Localitate : BaseEntity
    {
        [Required]
        public string Nume { get; set; }
        [Required]
        public int JudetID { get; set; }
        [Required]
        public virtual Judet Judet { get; set; }

        public Localitate() { }
    }
}

Here's how my request looks:

public class LocalitateRequest
{
    public string Nume { get; set; }
    public int JudetID { get; set; }
}

When I create a Localitate object, how should I do it? Do I need to fill the navigation property too, or is the int JudetID enough?

If it is enough, I'm encountering another problem - if I insert a JudetID that doesn't exist, I don't get any error (and I think I should, my DB would do that if I would be doing an insert statement).

CodePudding user response:

When I create a Localitate object, how should I do it? Do I need to fill the navigation property too, or is the int JudetID enough?

You can fill in the foreign ID if you wish, but this is very non-intuitive. Think about it, you know what entity you want to link your object to by name, right? So a more natural way of building your object would be like:

context.Localitati.Add(new()
{
    Nume = "meep",
    Judet = context.Judete.First(w => w.Nume = "moop")
});

To avoid repeated lookups, you can use dictionaries to memoize objects. Either way, you need to fill in either the ID or the foreign entity's ID field (which can be done by selecting it out).

if I insert a JudetID that doesn't exist, I don't get any error

Sure, because that's not a foreign key. Either declare it as such with the [ForeignKey] attribute, or use the correct naming convention: JudetId.

  • Related