0

I have a little tricky many to many question. I have two classes Character and Weapon. These two have a bridge table called WeaponCharacter, this is a many to many relationship.

enter image description here

At this moment, A Character can own one weapon of each kind, but a Character can't own two identical Weapons. Picture belows describes how I want to do.

enter image description here

The upper part is how the code is currently, and below is how I want it to be, or a similar solution.

This is the method that handles the transaction for buying weapons.

    [HttpGet]
    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)
        {
            character.Weapons.Add(weapon);
            character.Gold -= (int)weapon.Price;
            ctx.SaveChanges();
        }

        return RedirectToAction("Index", "Game");
    }

What I've done:

I did add Quantity once in WeaponCharacter but then the ICollections for Weapon and Character got really messed up.

This can be read here: ASP.net create many to many entity in C#

Goal:

I want a character to be able to own mulitple copies of same weapon aswell.

Community
  • 1
  • 1
Kokefa
  • 85
  • 9
  • It's as Sean Lange says, I want a character to be able to own multiple copies of the same weapon. Is many to many wrong in this situation? Could probably be easier just to make an inventory table, that takes weaponIds. – Kokefa Sep 25 '15 at 14:06
  • 1
    you might be better off in the long run if you remove the quantity column and just have a table with `WeaponCharacterId` (Key), `WeaponId` and `CharacterId`, and just keep inserting the same weapon and character id's. This would give you flexibility to have different optimizations for the same weapon for each character – JamieD77 Sep 25 '15 at 14:06
  • @JamieD77 that's sounds a lot easier. Being alone in a project tends to keep your thinking inside the box sometimes. I will go with that solution. – Kokefa Sep 25 '15 at 14:10

1 Answers1

1

As JamieD77 mentioned in comments.

you might be better off in the long run if you remove the quantity column and just have a table with WeaponCharacterId (Key), WeaponId and CharacterId, and just keep inserting the same weapon and character id's. This would give you flexibility to have different optimizations for the same weapon for each character.

Kokefa
  • 85
  • 9