麻烦与mongoDB。该物业' _id'类型...不能使用元素名称' _id'

时间:2014-06-13 14:21:03

标签: 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;
    }
}

比我在mongoDB中提取一些文件

var collection = database.GetCollection<Recipe>("Recipes");
var doc = collection.FindAllAs<Recipe>(); // exception

为什么我得到这个例外

&#34;该物业&#39; _id&#39;类型&#39; CourseServer.Models.Recipe&#39;不能使用元素名称&#39; _id&#39;因为它已被财产“_id&#39;。&#34;

使用

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

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

4 个答案:

答案 0 :(得分:3)

_id由MongoDb保留。 尝试使用&#34; Id&#34;代替。

答案 1 :(得分:1)

我认为你的班级应该是这样的:

[DataContract]
    public class Recipe
    {
        public Recipe()
        {
            Title = "";
            Description = "";
            CategoryId = "";
            Cost = cost;
            ProductList = new List<string>();
        }

        [BsonId]
        public ObjectId _id { get; set; }

        [DataMember]
        public string Id
        {
            get { return _id.ToString(); }
            set { _id = ObjectId.Parse(value); }
        }    

        [DataMember]
        public string Title { get; set; }

        [DataMember]
        public string Description { get; set; }

        [DataMember]
        public int Cost { get; set; }

        [DataMember]
        public string CategoryId { get; set; }

        [DataMember]
        public List<string> ProductList { get; set; }  
    }

答案 2 :(得分:0)

答案 3 :(得分:0)

您是否尝试过也包括Bson元素名称 在模型上声明的代码示例

[BsonElement("ProductList")]

[Display(Name = "ProductList")]

public List<string> ProductList { get; set; }

也可以参考,https://www.c-sharpcorner.com/article/simple-crud-operation-using-asp-net-mvc-and-mongodb/