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.