Home > Net >  Blazor One to many Relation in Index View fails
Blazor One to many Relation in Index View fails

Time:09-10

I'm new in Blazor, EF and .Net core, and I have this issue. I have this 2 model Class, Mercancia and Clasificacion. There is a relationship one to many between Mercancia and Clasificacion, and in the list of Mercancia instead show the ClasificacionID I would like to show the Name of Clasificacion, but not works. This is how I have declared the models.

public partial class Mercancia
   {
       public Mercancia()
       {
           AlmacenItems = new HashSet<AlmacenItem>();
           RecepcionItems = new HashSet<RecepcionItem>();
           ValeItems = new HashSet<ValeItem>();
       }

       public int Id { get; set; }
       public string Nombre { get; set; } = null!;
       public int ClasificacionId { get; set; }
       public string Codigo { get; set; } = null!;
       public string? Descripcion { get; set; }
       public string Um { get; set; } = null!;
       public virtual Clasificacion Clasificacion { get; set; } = null!;
   }
   public partial class Clasificacion
   {
       public Clasificacion()
       {
           Mercancia = new HashSet<Mercancia>();
       }

       public int Id { get; set; }
       public string Nombre { get; set; } = null!;
       public string? Detalle { get; set; }

       public virtual ICollection<Mercancia> Mercancia { get; set; }
   }

and this is the Controller for Mercancia

 [Route("api/[controller]")]
    [ApiController]
    public class MercanciaController : Controller
    {
        private readonly IMercancias imercancias;
        public IActionResult Index()
        {            
            return View();
        }
        public MercanciaController(IMercancias imercancias)
        {
            this.imercancias = imercancias;
        }
        [HttpGet]
        public async Task<ActionResult<List<Mercancia>>> Get()
        {
            return await Task.FromResult(imercancias.Lista());
        }

        [HttpPost]
        public void Post(Mercancia mercancia)
        {
            imercancias.Adicionar(mercancia);
        }

        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            Mercancia u = imercancias.Obtener(id);
            if (u != null)
            {
                return Ok(u);
            }
            return NotFound();
        }

        [HttpPut]
        public void Put(Mercancia merca)
        {
            imercancias.Editar(merca);
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            imercancias.Eliminar(id);
            return Ok();
        }
    }

The Service

public interface IMercancias
    {
        public List<Mercancia> Lista();

        public void Adicionar(Mercancia u);

        public void Editar(Mercancia u);

        public Mercancia Obtener(int id);

        public void Eliminar(int id);
    }
    public class GestionMercancias : IMercancias
    {
        readonly RaicesDBContext context = new();
        public GestionMercancias(RaicesDBContext context)
        {
            this.context = context;
        }
        public void Editar(Mercancia u)
        {
            try
            {
                context.Entry(u).State = EntityState.Modified;
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }

        public void Eliminar(int id)
        {
            try
            {
                Mercancia? u = context.Mercancias.Find(id);
                if (u != null)
                {
                    context.Mercancias.Remove(u);
                    context.SaveChanges();
                }
                else
                {
                    throw new ArgumentNullException();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }

        public List<Mercancia> Lista()
        {
            try
            {
                return context.Mercancias.ToList();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }

        public Mercancia Obtener(int id)
        {
            try
            {
                Mercancia? u = context.Mercancias.Find(id);
                if (u != null)
                {
                    return u;
                }
                else
                {
                    throw new ArgumentNullException();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }

        public void Adicionar(Mercancia u)
        {
            try
            {
                context.Mercancias.Add(u);
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
    }

And the view

@page "/mercancias"
@inject HttpClient client
@inject IJSRuntime js
<h3>Mercancías</h3>
<small>Adiciona mercancías.</small>
<div >
    <a  href="mercancias/create"><i ></i> Nuevo</a>
</div>
<br>
@if (mercancias == null)
{
    <text>Loading...</text>
}
else if (mercancias.Count == 0)
{
    <text>No Records Found.</text>
}
else
{
    <table >
        <thead>
            <tr>
                <th>Id</th>
                <th>Mercancia</th>
                <th>Clasificacion</th>
                <th>Codigo</th>
                <th>UM</th>
                <th>Detalles</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (Mercancia merc in mercancias)
            {
                <tr>
                    <td>@merc.Id</td>
                    <td>@merc.Nombre</td>
                    <td>@merc.Clasificacion.Nombre</td> **HERE THE PROBLEM**
                    <td>@merc.Um</td>
                    <td>@merc.Descripcion</td>
                    <td>
                        <a  href="mercancias/editar/@merc.Id">Edit</a>
                        <button  @onclick="@(() => Delete(merc.Id))">Delete</button>
                    </td>
                </tr>
            }
        </tbody>
    </table>
}
@code {
    List<Mercancia> mercancias { get; set; }
    protected override async Task OnInitializedAsync()
    {
        mercancias = await client.GetFromJsonAsync<List<Mercancia>>("api/Mercancia");
    }
    async Task Delete(int Id)
    {
        var merca = mercancias.First(x => x.Id == Id);
        if (await js.InvokeAsync<bool>("confirm", $"Do you want to delete {merca.Nombre}'s ({merca.Id}) Record?"))
        {
            await client.DeleteAsync($"api/Mercancia/{Id}");
            await OnInitializedAsync();
        }
    }
}

CodePudding user response:

First, a cycle relation in my Model

public partial class Mercancia
{
  public Mercancia()
  {
    AlmacenItems = new HashSet<AlmacenItem>();
    RecepcionItems = new HashSet<RecepcionItem>();
    ValeItems = new HashSet<ValeItem>();
  }

  public int Id { get; set; }
  public string Nombre { get; set; } = null!;
  public int ClasificacionId { get; set; }
  public string Codigo { get; set; } = null!;
  public string? Descripcion { get; set; }
  public string Um { get; set; } = null!;
  public virtual Clasificacion Clasificacion { get; set; } = null!;
}

public partial class Clasificacion
{
  public Clasificacion()
  {
    //Mercancia = new HashSet<Mercancia>();
  }

  public int Id { get; set; }
  public string Nombre { get; set; } = null!;
  public string? Detalle { get; set; }

  //public virtual ICollection<Mercancia> Mercancia { get; set; }
}

Then, I must "Include" the relation in the Controler.

public List<Mercancia> Lista()
{
  try
  {
    return context.Mercancias.Include(m => m.Clasificacion).ToList();
  }
  catch (Exception ex)
  {
    throw new Exception(ex.ToString());
  }
}
  • Related