我有一个具有以下模型的 WebAPI:
public class Dog
{
public string name { get; set; }
public string breed { get; set; }
public string size { get; set; }
public CoatType coatType { get; set; }
private List<Dog> dogs;
}
public enum CoatType
{
Long,
Short,
Curly
};
我的存储库如下所示:
public class AnimalRepository
{
private const string CacheKey = "AnimalStore";
public AnimalRepository()
{
var context = HttpContext.Current;
if (context != null)
{
if (context.Cache[CacheKey] == null)
{
var contacts = new Dog[]
{
new Dog { name = "Lassie", breed = "Collie", size = "Medium", coatType = CoatType.Long },
new Dog { name = "Fido", breed = "Labrador", size = "Large" , coatType = CoatType.Short},
};
context.Cache[CacheKey] = contacts;
}
}
}
public Dog[] GetAllAnimals()
{
var context = HttpContext.Current;
if (context != null)
{
return (Dog[])context.Cache[CacheKey];
}
return new Dog[]
{
new Dog
{
name = "",
breed = "Placeholder",
size = "Placeholder",
coatType = CoatType.Curly
}
};
}
public bool SaveAnimal(Dog animal)
{
var context = HttpContext.Current;
if (context != null)
{
try
{
var currentData = ((Dog[])context.Cache[CacheKey]).ToList();
bool nameExists = false;
if (nameExists != true)
{
currentData.Add(animal);
context.Cache[CacheKey] = currentData.ToArray();
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
return false;
}
}
我的控制器看起来像这样:
public class AnimalController : ApiController
{
private AnimalRepository repository;
public AnimalController()
{
this.repository = new AnimalRepository();
}
public Dog[] Get()
{
return this.repository.GetAllAnimals();
}
public HttpResponseMessage Post(Dog animal)
{
this.repository.SaveAnimal(animal);
var response = Request.CreateResponse<Dog>(System.Net.HttpStatusCode.Created, animal);
return response;
}
我的 Index.cshtml 看起来像这样:
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">
<a href="~/">Field<b>Connect</b></a></p>
</div>
</div>
</header>
<div id="body">
<ul id="animals"></ul>
<form id="saveForm" method="post">
<h3>New Dog</h3>
<p>
<label for="name">Name:</label>
<input type="text" name="name" />
</p>
<p>
<label for="breed">Breed:</label>
<input type="text" name="breed" />
</p>
<p>
<label for="size">Size:</label>
<input type="text" name="size" />
</p>
<p>
<label for="coatType">Coat Type:</label>
<select name="coatType">
<option value="Long">Long Hair</option>
<option value="Short">Short Hair</option>
<option value="Curly">Curly Hair</option>
</select>
</p>
<input type="button" id="saveAnimal" value="Save" />
</form>
</div>
@section scripts{
<script type="text/javascript">
$(function () {
$.getJSON('/api/animal', function (contactsJsonPayload) {
$(contactsJsonPayload).each(function (i, item) {
$('#animals').append('<li>' + item.name + '</li>');
});
});
});
$('#saveAnimal').click(function () {
$.post("api/animal",
$("#saveForm").serialize(),
function (value) {
$('#animals').append('<li>' + value.name + '</li>');
},
"json"
);
});
</script>
}
所有这一切都很好。我的网页上显示了属于已定义集合的两只狗。然而,我想要做的是在我将一只新狗保存到收藏之前,我想检查该狗当前是否存在于收藏中。所以我开始在 AnimalRepository.cs 中的代码行之后实现一个 forach 循环: bool nameExists = false; 行代码。
// Check to see if the name of the animal already exists
for (int i = 0; i < currentData.Count; i++)
{
foreach (var item in currentData[i])
{
if (item.Equals(currentData[i].name))
{
nameExists = true;
}
}
}
但是当我构建时,我得到一个错误,除非我实现 IEnumerable,否则我无法遍历这个集合,所以我这样做了。我在我的类中添加了:IEnumerable 以从接口继承,并将以下代码添加到我的 Dog 类中,完成如下......
public class Dog : IEnumerable<Dog>
{
public string name { get; set; }
public string breed { get; set; }
public string size { get; set; }
public CoatType coatType { get; set; }
private List<Dog> dogs;
public IEnumerator<Dog> GetEnumerator()
{
if (dogs != null)
{
foreach (Dog dog in dogs)
{
if (dog == null)
{
break;
}
yield return dog;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
// Lets call the generic version here
return this.GetEnumerator();
}
}
public enum CoatType
{
Long,
Short,
Curly
};
但是现在当我运行代码时,我看到的是“未定义”,而不是在页面顶部看到狗的名字。我尝试返回字符串类型的 IEnumerable 而不是 Dog,但这没有帮助。有什么想法可以解决这个问题吗?