几个角色可以有几种武器和几种同类
Several characters can have several weapons and several of same kind
我有一个有点棘手的多对多问题。我有两个 类 Character
和 Weapon
。这两个有一个桥table叫做WeaponCharacter
,这是一个多对多的关系。
此时,一个Character
可以拥有每一种weapon
一个,但是一个Character
不能拥有两个相同的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");
}
我做了什么:
我确实在 WeaponCharacter
中添加了一次数量,但是 Weapon
和 Character
的 ICollections
真的搞砸了。
可以在这里阅读:ASP.net create many to many entity in C#
目标:
我希望一个角色也能够拥有相同武器的多个副本。
正如评论中提到的 JamieD77。
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.
我有一个有点棘手的多对多问题。我有两个 类 Character
和 Weapon
。这两个有一个桥table叫做WeaponCharacter
,这是一个多对多的关系。
此时,一个Character
可以拥有每一种weapon
一个,但是一个Character
不能拥有两个相同的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");
}
我做了什么:
我确实在 WeaponCharacter
中添加了一次数量,但是 Weapon
和 Character
的 ICollections
真的搞砸了。
可以在这里阅读:ASP.net create many to many entity in C#
目标:
我希望一个角色也能够拥有相同武器的多个副本。
正如评论中提到的 JamieD77。
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.