gpt4 book ai didi

c# - 将复杂对象序列化到 mongoDB

转载 作者:太空宇宙 更新时间:2023-11-03 16:12:55 25 4
gpt4 key购买 nike

我有几个密切相关的问题,所以我将它们分组在这个问题下。

我正在尝试使用 C# 和 mongoDB 驱动程序和数据库为我的对象模型创建一个持久数据库。我希望能够存储我所有的用户对象——在这些用户中应该是 session (一个“列表”或类似的数据结构),并且在每个 session 中是他们创建的不同事件和记录(也是列表)。当发出新请求时 - 最初我通过其标识符查找用户。如果它存在,我创建一个 session 对象。将该 session 对象添加到用户的 session 列表,然后进行适当的更新(向 session 添加事件或记录)。 (否则我创建一个新用户 - 将其添加到数据库,然后执行前面的步骤)

我的问题是,当我执行 "collection.save(user)" 时或 "find(user)"我遇到错误 - 无法序列化抽象类。 Per the documentation我应该能够使用“自动映射”功能,所以我认为它可以开箱即用。那太好了。我希望我的 db 对象显示为我的用户对象的容器,就像在 UsersDb 类中一样。

如果没有 - 是否有合适的“mongodb”容器类我可以使用(即代替“List<Session> ”使用 -> BsonList<Session> )?另外我应该如何在我的类中实例化容器?如果它们是由序列化程序生成的,我应该在构造函数中启动它们吗?另外,我如何在我的类中存储任意“动态”数据(只是一些常规的 json)

我正在创建一个像这样的基本集合:

public class UsersDb 
{
public UsersDb()
{
MongoServerSettings settings =new MongoServerSettings();
settings.Server = new MongoServerAddress("localhost",27017);
MongoServer server = new MongoServer(settings);
MongoDatabase db = server.GetDatabase("defaultDb");
Users = db.GetCollection<User>("Users");
//Users.Drop();
}

public MongoCollection<User> Users { get; set; }
}

这是我的用户类:我已经在这里遇到问题,因为构造函数需要能够创建一个 session 列表——但是如果它被 mongo 驱动程序序列化会怎样?

public User()
{
SessionComparer uc = new SessionComparer();
Sessions = new List<Session>();;
}

public ObjectId Id { get; set; }
public string Udid { get; set; }
public DateTime EnrollDate { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public List<Session> Sessions { get; set; }

我的类(class)

public class Session
{
public Session()
{
Events = new List<Event>();
Records = new List<Record>();
}
public string SessionId { get; set; }
public DateTime Time { get; set; }
public dynamic Parameters { get; set; }
public IList<Event> Events { get; set; }
public IList<Record> Records { get; set; }
}

记录

public class Record
{
public Record()
{
RecordId = Guid.NewGuid().ToString();
CreatedAt = DateTime.Now;
}
public string Name { get; set; }
public string RecordId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime Time { get; set; }
public dynamic Data { get; set; }
}

和事件

public class Record
{
public Record()
{
RecordId = Guid.NewGuid().ToString();
CreatedAt = DateTime.Now;
}
public string Name { get; set; }
public string RecordId { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime Time { get; set; }
public dynamic Data { get; set; }
}

最佳答案

你不能反序列化动态。为了使用真实的类,您需要更严格的东西。

可能以下解决方法是合适的:

[BsonKNownTypes(typeof(Implementation1))]
[BsonKNownTypes(typeof(Implementation2))]
public class DynamicModelHere {}
public class Implementation1 : DynamicModelHere { property, property, property }
public class Implementation2 : DynamicModelHere { property, property, property }

关于c# - 将复杂对象序列化到 mongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16834608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com