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.
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.
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.