Skip to content Skip to sidebar Skip to footer

Asp.net Create Many To Many Entity In C#

I'm trying to create an many to many entity in asp.net C#. I have looked at the student/course example before and it is logical but something is literally wrong when I try use it i

Solution 1:

I might be wrong as I'm used to EntityFramework for Code-First aproach, but shouldn't your Character class have an ICollection<Weapon> property instead of 'WeaponCharacter'? On my experience (With EF, latest version) the ICollection would be automatically mapped to the WeaponCharacter table as you add items to that collection.

Example of a working many-to-many relationship, using EF-CodeFirst, where Prescricao has a many-to-many relationship with Remedio:

publicclassPrescricao
{
    // Hidden Properties///<summary>/// Remédios prescritos para o paciente.///</summary>publicvirtual ICollection<Remedio> Remedios { get; set; }

    publicPrescricao()
    {
        Remedios = new List<Remedio>();
    }

}

publicclassRemedio
{
    ///<summary>/// Prescrições que incluem o remédio.///</summary>publicvirtual ICollection<Prescricao> Prescricoes { get; set; }

    publicRemedio()
    {
        Prescricoes = new List<Prescricao>();
    }

Adding something to the relationship:

var pres1 = new Classes.Prescricao()
        {
            DataEmissao = DateTime.Now,
            DataLimite = DateTime.Now.AddMonths(1),
            Descricao = "Prescrição teste.",
            Medico = m1,
            Paciente = p1,
            Status = Classes.PrescricaoStatus.Pendente
        };
var r1 = new Classes.Remedio()
        {
            NomeComercial = "Aspirina",
            PrecoMedio = 12.49m,
            PrincipioAtivo = "Whatever",
            Status = Classes.RemedioStatus.Aprovado
        };

        context.Remedios.Add(r1);
        pres1.Remedios.Add(r1);
        context.Prescricoes.Add(pres1);

(Was going to add this as a comment as I don't think this solves the issue at hand but I can't comment just yet)

Post a Comment for "Asp.net Create Many To Many Entity In C#"