删除父对象后如何存储值

时间:2019-07-01 09:49:23

标签: c# asp.net-mvc

我需要独立于父对象存储一个值,因此,如果要删除它,我的值将保留在程序中。

我没有使用数据库,我的MVC已链接到带有存储库的库框架

模型

    namespace FarmMVC.Models
    {
      public abstract class AnimalViewModel
      {
        protected AnimalViewModel()
        {

        }
        protected AnimalViewModel(AnimalBase a)
        {
          Name = a.Name;
          Age = a.Age;
          Weight = a.Weight;
          Breed = a.Breed;
          Gender = a.Gender;
          ParticularSigns = a.ParticularSigns;
          Color = a.Color;
          Meat = a.Meat;         
        }

          public int Meat { get; set; }
          public int MeatProduction { get; set; }
      }
    }

控制器

    namespace FarmMVC.Controllers
    {
      public class AnimalsController : Controller
      {
        public ActionResult GoatMilk(string name)
        {
          var rep = new GoatRepository();
          var goat = rep.GetByName(name);

          var model = FarmFactory.CreateAnimalModel<GoatViewModel>(goat) as GoatViewModel;

          model.MilkProduction = rep.MilkProduction(goat);

          var list = rep.GetAll().Select(g => FarmFactory.CreateAnimalModel<GoatViewModel>(g)).ToList();

          return View("~/Views/Animals/Goats.cshtml", list);
        }
      }  
    }

视图

   @model IEnumerable<FarmMVC.Models.GoatViewModel>

   <div class="panel panel-default">
     <div class="panel-body">
        @Html.DisplayNameFor(model => model.MeatProduction)
        @Model.Sum(i => i.Meat)
     </div>
   </div>

如何跟踪正在处理的对象

  namespace FarmMVC.Factories
  {
    public static class FarmFactory
    {
      public static T CreateAnimalModel<T>(AnimalBase a)
        where T : AnimalViewModel
      {

          return (T)Activator.CreateInstance(typeof(T), a);

      }
    }
  }

方法

   namespace Farm.Repositories
   {
     public class GoatRepository : GenericRepository<Goat>
     {
       public int MeatProduction(Goat goat)
       {
          if (goat == null)
          {
              throw new ArgumentNullException(nameof(goat));
          }


          if (goat.Age > 13 && goat.Weight >= 50 && goat.Weight <= 100)
          {
              goat.Meat += getrandom.Next(3, 6);
              Remove(goat);
          }
          else if (goat.Weight > 100)
          {
              goat.Meat += getrandom.Next(5, 9);
              Remove(goat);
          }
          else if (IsDead(goat))
          {
              goat.Meat += getrandom.Next(2, 4);
              Remove(goat);
          }

          return goat.Meat;
        }
      }
    }

在控制器的最后两行中,由于我正在使用IEnumerables,因此我需要将所有内容存储在列表中,但是由于我已经删除了该方法中的对象,因此我什么也得不到,但是我需要跟踪肉价值

谢谢

0 个答案:

没有答案