Home > Blockchain >  EF Core does not saving changes on relation table
EF Core does not saving changes on relation table

Time:10-25

I'm working with EF Core and I have a model with foreign key as:

public class Advertiser
{
    public int AdvertiserId { get; set; }

    public string Name { get; set; } = string.Empty;

    [ForeignKey(nameof(AddressId))]
    public virtual Address? Address { get; set; }

    public int? AddressId { get; set; }
    ...
}

public void Configure(EntityTypeBuilder<Advertiser> builder)
    {
     ...
     builder.HasOne(adv => adv.Address);
    }

As you can see I have an advertiser model and addressId foreignkey referencing the Address entity.

So that is working well, now I want to insert data in Advertiser and Address entities in database as:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(CreateViewModel model)
    {

      var advertiserModel = new Advertiser
        {
            Name = model.Name,
            ...
        };

       if (advertiserModel.Address != null)
        {
            advertiserModel.Address.AddressLine1 = model.AddressLine1;
            advertiserModel.Address.AddressLine2 = model.AddressLine2;
            advertiserModel.Address.City = model.City;
            advertiserModel.Address.State = model.State;
            advertiserModel.Address.ZipCode = model.ZipCode;
            advertiserModel.Address.PhoneNumber = model.PhoneNumber;
            advertiserModel.Address.FaxNumber = model.FaxNumber;
        }

         await _advertisersService.CreateAdvertiserAsync(advertiserModel);
    }

Service:

public async Task<Advertiser> CreateAdvertiserAsync(Advertiser advertiser)
    {
        await _db.Advertisers.AddAsync(advertiser);
        await _db.SaveChangesAsync();

        return advertiser;
    }

The problem is that is not populating the address table and also has null foreign key on advertisers table. What am I doing wrong? Why is no saving data on relation table?

CodePudding user response:

Address is null by default.

public virtual Address? Address { get; set; }

An Advertiser won't have an address unless you set one, eg

var advertiserModel = new Advertiser
{
    Name = model. Name,
    Address = new Address(),
    ...
};
  • Related