MongoDB 的问题。类型的属性“_id”...不能使用元素名称“_id”

Vla*_*tov 6 c# mongodb asp.net-mvc-4

我使用 ASP .NET MVC4 WebAPI 并且我有一些类

public class Recipe
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string _id { get; set; }

    [BsonElement]
    [Display(Name = "Title")]
    public string Title { get; set; }

    [BsonElement]
    [Display(Name = "Description")]
    public string Description { get; set; }

    [BsonElement]
    [Display(Name = "Cost")]
    public int Cost { get; set; }

    [BsonElement]
    [Display(Name = "CategoryId")]
    public string CategoryId { get; set; }

    [BsonElement]
    [Display(Name = "ProductList")]
    public List<string> ProductList { get; set; }

    [BsonConstructor]
    public Recipe(string title, string description, string type, int cost, List<string> productList)
    {
        Title = title;
        Description = description;
        CategoryId = type;
        Cost = cost;
        ProductList = productList;
    }
}
Run Code Online (Sandbox Code Playgroud)

比我在 mongoDB 中取一些文件

var collection = database.GetCollection<Recipe>("Recipes");
var doc = collection.FindAllAs<Recipe>(); // exception
Run Code Online (Sandbox Code Playgroud)

为什么我得到这个异常

“‘CourseServer.Models.Recipe’类型的属性‘_id’不能使用元素名称‘_id’,因为它已被属性‘_id’使用。”

我有类 Person 我使用相同的属性并且它可以工作。

public class Person
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string _id { get; set; } // and other some fields
Run Code Online (Sandbox Code Playgroud)

Dou*_*son 3

_id 由 MongoDb 保留。尝试使用“Id”代替。