ASP.net create many to many entity in C#

廉价感情. 提交于 2019-12-11 05:48:29

问题


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 in my own code.

Here is the code where I'm stuck.

    [HttpPost]
    public ActionResult BuyWeapon(int weaponId)
    {
        string currentUserId = User.Identity.GetUserId();

        var ctx = new DAL.ProjectStrawberryEntities();

        Character character = ctx.Characters.FirstOrDefault(c => c.AccountId == currentUserId);
        Weapon weapon = ctx.Weapons.FirstOrDefault(w => w.Id == weaponId);

        if (character.Gold - weapon.Price >= 0)
        {
            // Add weapon to character

            character.Gold -= (int)weapon.Price;
        }

        return View();
    }

The only properties Character and Weapon has is WeaponCharacter, which is my bridge table for Weapon and Character.

Here are my Character and Weapon models from my database.

public partial class Character
{
    public Character()
    {
        this.WeaponCharacters = new HashSet<WeaponCharacter>();
    }

    *Removed wall of propeties*

    public virtual AspNetUser AspNetUser { get; set; }
    public virtual Class Class { get; set; }
    public virtual Gender Gender { get; set; }
    public virtual ICollection<WeaponCharacter> WeaponCharacters { get; set; }
}

public partial class Weapon
{
    public Weapon()
    {
        this.WeaponCharacters = new HashSet<WeaponCharacter>();
    }

    *Removed wall of propeties*

    public virtual WeaponType WeaponType { get; set; }
    public virtual ICollection<WeaponCharacter> WeaponCharacters { get; set; }
}

public partial class WeaponCharacter
{
    public int CharacterId { get; set; }
    public int WeaponId { get; set; }
    public int Quantity { get; set; }

    public virtual Character Character { get; set; }
    public virtual Weapon Weapon { get; set; }
}

I cropped out some properties since they are unnecessary.

Shouldn't Character have an ICollection<Weapon>? Am I wrong to use a many to many relation for this?

The goal I'm trying to reach is: I want a character to buy a weapon, it is possible to buy several of the same weapon but only once per click.


回答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:

public class Prescricao
{
    // Hidden Properties

    /// <summary>
    /// Remédios prescritos para o paciente.
    /// </summary>
    public virtual ICollection<Remedio> Remedios { get; set; }

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

}

public class Remedio
{
    /// <summary>
    /// Prescrições que incluem o remédio.
    /// </summary>
    public virtual ICollection<Prescricao> Prescricoes { get; set; }

    public Remedio()
    {
        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)



来源:https://stackoverflow.com/questions/32608596/asp-net-create-many-to-many-entity-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!