Search code examples
c#entity-relationship

c# Entity Framework - Relationship one-to-one


I need to make a relationship beetween Product and Mark, in the entity Product i select the "MarcaId" to Show the name the Mark. But is not working, only show me the IDs.

    namespace Aplicacao.Models
    {
        public class Marca
        {

            public int MarcaId { get; set; }
            public string Descricao { get; set; }

         public virtual Produto Produtos { get; set; }     

    }
} 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Aplicacao.Models
{
    public class Produto
    {
        public int ProdutoID { get; set; }
        public string Descricao { get; set; }
        public decimal Preco { get; set; }
        public int MarcaId { get; set; }     
    }
}

Solution

  • You need to add the navigation property to Marca in the Produto class as well. Something like this:

    public class Produto
    {
        public int ProdutoId { get; set; }
        public string Descricao { get; set; }
        public decimal Preco { get; set; }
        public int MarcaId { get; set; }     
    
        public virtual Marca Marca { get; set; }
    }
    

    Notice that I also renamed the "ProdutoID" to "ProdutoId".

    Also, making an assumption based on the name of your "Produtos" property in the Marca class, I believe you want to declare it as a collection such as:

    public virtual ICollection<Produto> Produtos { get; set; }