C# mongodb.driver ORM ,插入数据忽略属性

寿毅庵
2023-12-01
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            MongoClient client = new MongoClient("mongodb://127.0.0.1:27017");

            //连接数据库,如果不存在,则新建
            var db = client.GetDatabase("test");
            //获取集合
            var collection = db.GetCollection<Grade>("grade");

            Student stu = new Student
            {
                ID = 1,
                Name = "哈哈",
                Sex = "男",
                test1="123"
            };


            Student stu1 = new Student
            {
                ID = 1,
                Name = "哈哈",
                Sex = "男"
            };


            Grade grade = new Grade { ID = 1, Name = "1", students = new List<Student> { stu, stu1 } };

            //添加数据
            collection.InsertOne(grade);


            List<Grade> grades= collection.Find(Builders<Grade>.Filter.Eq("Name", "1")).ToList();
            //删除数据
            //collection.DeleteOne(Builders<Student>.Filter.Eq("Name", "哈哈"));

            修改数据
            //var filter = Builders<Student>.Filter.Eq("Name", "哈哈");
            //var update = Builders<Student>.Update.Set("Sex", "女");
            //collection.UpdateOne(filter, update);//UpdateOne修改一条,UpdateMany修改全部

            查询数据
            //var res = collection.Find(Builders<Student>.Filter.Eq("Name", "哈哈")).ToList();




            //await collection.InsertOneAsync(document);
            Console.ReadKey();


        }
    }
}

添加[BsonIgnore]属性

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Student
    {
        public ObjectId _id { get; set; }
        public int ID { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }

        [BsonIgnore]
        public string test1 { get; set; }

        public void test()
        {
            Console.WriteLine(123);
        }
    }


    public class Grade
    {
        public ObjectId _id { get; set; }
        public int ID { get; set; }
        public string Name { get; set; }

        public List<Student> students { get; set; }
    }
}

 类似资料: