Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在ASP.NET MVC中自动增加id_C#_Asp.net Mvc_Visual Studio - Fatal编程技术网

C# 在ASP.NET MVC中自动增加id

C# 在ASP.NET MVC中自动增加id,c#,asp.net-mvc,visual-studio,C#,Asp.net Mvc,Visual Studio,这是我的一些代码,前三个事件已经在系统中定义,但当用户想要创建另一个事件时,事件ID应该是++1。我无法定义事件ID。我应该用哪种方式 using System.Collections.Generic; namespace Events.Models { public interface IRepository { IEnumerable<Event> Events { get; } void AddEvent(Event new

这是我的一些代码,前三个事件已经在系统中定义,但当用户想要创建另一个事件时,
事件ID
应该是
++1
。我无法定义
事件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);
        }
    }
}
使用System.Collections.Generic;
命名空间事件.模型
{
公共接口假定
{
IEnumerable事件{get;}
无效添加事件(事件newEvent);
}
公共类MemoryRepository:IRepository
{
私有列表事件=新列表
{
新事件{id=1,Name=“Event A”,DOB=System.DateTime.Now,Duration=60},
新事件{id=2,Name=“Event B”,DOB=System.DateTime.Now,Duration=60},
新事件{id=3,Name=“Event C”,DOB=System.DateTime.Now,Duration=60},
};
公共IEnumerable事件=>事件;
公共无效添加事件(事件newEvent)
{
events.Add(newEvent);
}
}
}
List()数据类型具有内置的ID参数

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

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

您必须得到事件ID的最后ID并在事件中添加一个事件,当事件在中间删除一个事件之后,应该发生什么?应该是-1,但我不能得到最后的IDE。您可以在您的RePO类中创建一个看起来像这样的方法:<代码> int增加ID(int id){返回ID + 1;} <代码>