2

Friends, it had a "person" table where it records the user's information. Now I created an "address" table to store the user's address information.

Now I need to reorganize my code because I'm having relationship problems. These are my files:

Person.cs

using LojaVirtual.Libraries.Lang;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace LojaVirtual.Models
{
    public class person
    {
        /* PK */
        [Key]
        public int cod_person { get; set; }

        public string name { get; set; }
        public DateTime date { get; set; }
        public string gender{ get; set; }
        .
        .
        public string email { get; set; }
        public string password { get; set; }
        public addres addres { get; set; }
        
        [ForeignKey("cod_person")]
        public virtual ICollection<order> Order { get; set; }
    }
}

Address.cs

using System;
using System.Collections.Generic;
using LojaVirtual.Libraries.Lang;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace LojaVirtual.Models
{
    public class address
    {
        [Key]
        public int cod_address{ get; set; }

        public string { get; set; }
        public string neighborhood{ get; set; }

        public string city { get; set; }
        public string state{ get; set; }
        .
        .

        [ForeignKey("person")]
        public int? cod_person { get; set; }

        public person person { get; set; }
    }
}

LojaVirtualContext.cs


using LojaVirtual.Models;
using LojaVirtual.Models.ProdutoAgregador;
using Pomelo.EntityFrameworkCore.MySql;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;


namespace LojaVirtual.Database
{
    public class LojaVirtualContext : DbContext
    {
        /*
         * EF Core - ORM
         * ORM -> Bibliteca mapear Objetos para Banco de Dados Relacionais
         */
        public LojaVirtualContext(DbContextOptions<LojaVirtualContext> options) : base(options)
        {

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<person>()
                .HasOne<address>(s => s.address)
                .WithOne(ad => ad.person)
                .HasForeignKey<address>(ad => ad.cod_person);

        }
        public DbSet<person> person { get; set; }
        public DbSet<order> order{ get; set; }
        public DbSet<address> addres { get; set; }
    }
}

Here on this line, I get an error that I can't solve:

public List<order> ObterTodosPedidosPorSituacao(string status)
{
 return _banco.order
       .Include(a => a.order_situation)
       .Include(a => a.person)
       .ThenInclude(p => p.address)
       .Where(a => a.Situation == status).ToList();}

I need to access the fields of the address table, through the person table. I believe that's it, but I get the error:

MySql.Data.MySqlClient.MySqlException: 'Unknown column 'a.addresscod_address' in 'field list''

I also tried: a.person.address, but the same error occurs.

I appreciate if anyone can analyze.

1
  • What is _banco? Could you please include the full code including the constructor?
    – Serge
    Dec 19, 2020 at 23:01

2 Answers 2

0

You have relationship misconfiguration here

modelBuilder.Entity<person>()
    .HasOne<address>(s => s.address)
    .WithOne(ad => ad.person)
    .HasForeignKey<person>(ad => ad.cod_person); // <-- problem: ad is person

The type of the ad in the last line is the type of the HasForeignKey generic type argument. You should read is this way - the generic type argument of HasForeignKey is the entity type containing the foreign key.

So what are you doing here is essentially configuring the PK of the person entity to be used also as FK to the address, which invalidates the intended FK in address (because fluent configuration has higher priority/overrides conventions and data annotations).

With that being said, simply map the address as dependent entity of the one-to-one relationship (the entity with FK) by changing the generic type argument:

.HasForeignKey<address>(ad => ad.cod_person);

Also consider removing (and avoiding in general) the ForeignKey attributes. They have different semantic depending on the place applied (on navigation property the specify the associated FK property name, and on FK property they specify the associated navigation property name) and can easily be messed up as in your case:

[ForeignKey("cod_person")] // <-- wrong, points to self
public int? cod_person { get; set; }
public person person { get; set; }

It should be either

[ForeignKey("person")] // the name of the below navigation property
public int? cod_person { get; set; }
public person person { get; set; }

or

public int? cod_person { get; set; }
[ForeignKey("cod_person")] // the name of the above FK property
public person person { get; set; }

but as I said earlier, better avoid using that attribute and configure relationships with fluent API where needed.

2
  • Thanks for the feedback. I updated the code, received the following: MySql.Data.MySqlClient.MySqlException: 'Unknown column 'a.addresscod_address' in 'field list''
    – E. Biagi
    Dec 21, 2020 at 16:58
  • Now I'm getting this result: 'The property or navigation 'person' cannot be added to the entity type 'address' because a property or navigation with the same name already exists on entity type 'address
    – E. Biagi
    Dec 21, 2020 at 18:23
0

This should work:

public List<order> ObterTodosPedidosPorSituacao(string status)
{
    return _banco.order
       .Include(a => a.order_situation)
       .Include(a => a.person)
       .ThenInclude(p => p.address)
       .Where(a => a.Situation == status).ToList();
}

But I'm only guessing due to not all code is included. If I could suggest something - in c# exists strict naming convention. It is not big deal but it helps to work in teams :).

edit: I saw other problem with data annotation. [ForeignKey("cod_person")] -this is redundant. Remember to perform db migration after changes.

2
  • Thanks for the feedback. I updated the code, received the following: MySql.Data.MySqlClient.MySqlException: 'Unknown column 'a.addresscod_address' in 'field list''
    – E. Biagi
    Dec 21, 2020 at 16:57
  • Now I'm getting this result: 'The property or navigation 'person' cannot be added to the entity type 'address' because a property or navigation with the same name already exists on entity type 'address'.'
    – E. Biagi
    Dec 21, 2020 at 18:23

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.