【问题标题】:Automatically increase id, in ASP.NET MVC在 ASP.NET MVC 中自动增加 id
【发布时间】:2018-10-21 07:41:16
【问题描述】:

这是我的一些代码,前三个事件已经在系统中定义,但是当用户想要创建另一个事件时,Event ID 应该是++1。我无法定义Event ID。我应该使用哪种方式?

using System.Collections.Generic;

namespace Events.Models 
{
    public interface IRepository 
    {
        IEnumerable<Event> Events { get; }
        void AddEvent(Event newEvent);
    }

    public class MemoryRepository : IRepository 
    {
        private List<Event> events= new List<Event> 
        {
            new Event { id = 1, Name = "Event A", DOB = System.DateTime.Now, Duration = 60 },
            new Event { id = 2, Name = "Event B", DOB = System.DateTime.Now, Duration = 60 },
            new Event { id = 3, Name = "Event C", DOB = System.DateTime.Now, Duration = 60 },
        };

        public IEnumerable<Event> Events=> events;

        public void AddEvent(Event newEvent) 
        {
            events.Add(newEvent);
        }
    }
}

【问题讨论】:

  • 您必须获取事件列表的最后一个 id 并在其中增加一个
  • 在中间的一个事件被移除后添加事件会发生什么?
  • 应该是 -1 但我无法获得最后一个 id
  • 您可以在您的 repo 类中创建一个方法,如下所示:int IncreaseId(int id) {return id +1;}

标签: c# asp.net-mvc visual-studio


【解决方案1】:

List() 数据类型有一个内置的 ID 参数。

因此,如果您在没有 ID 参数的情况下初始化 Event 列表,您仍然可以使用这种代码通过 ID 访问它们:

public Event GetEvent(int id) {
    if (events.Count > id)
        return events[id];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 2021-10-20
    • 2015-01-15
    • 1970-01-01
    • 2014-08-03
    • 2015-03-19
    相关资源
    最近更新 更多