Home > database >  When I take information from a database object, I get null, such as Car.Color = null
When I take information from a database object, I get null, such as Car.Color = null

Time:02-06

I had mistake, but does not understand where. When I`m add to my database object they saved correct, unfortunately not equals my image, maybe it`s my mistake. I need hint to where look. For the sake of simplicity, I will reduce my case to a car and its color, where each is an object and unique (one-to-one), so..

I have two object Car with Color to one-to-one relationship.

public class Car
{
    public Color Color { get; set; }
    public long ColorId { get; set; }

    [Key]
    public long Id { get; set; }
}

public class Color
{
    public Car Car { get; set; }
    public long CarId { get; set; }

    [Key]
    public long Id { get; set; }
}

I`m using Entity Framework, so for configuration used Fluent Api, and they look like as:

public void Configure(EntityTypeBuilder<Color> builder)
{
    builder.HasKey(k => k.Id);
            
    builder
        .HasOne(one => one.Car)
        .WithOne(with => with.Color)
        .HasForeignKey<Car>(fk => fk.CarId)
        .IsRequired();
}

In table i have Car with foreign key to Color, but foreign key in Color always equals to 0. How i understand it`s correct mapping at one to one. In this case, I thought so be it, but later when I wanted to get Car.Color I saw that it always returns null. It`s not issue in adding, because followed up him in debugger.

In my opinion it`s issue in save or there's something I can't guess. This is based on the fact that on the path to save and even at the time of saving it has a reference (Car.Color = object), but when you first get it out of the database it is empty, similarly:

{
    "Id": "1",
    "Color": null,
    "ColorId": 3
}

CodePudding user response:

Check out the Loading Related Data part of EF Core docs. By default EF does not load the related data. There are multiple ways to handle that, for example using Include:

var carWithColor = await context.Car
   .Include(c => c.Color)
   .Where(c => c.Id == ...)
   .FirstOrDefaultAsync();

P.S.

Having one-to-one relationships between colors and cars seems a bit strange to me.

  • Related