在mongodb和Entityframework中使用与相同的C#Poco类

在mongodb和Entityframework中使用与相同的C#Poco类,c#,entity-framework,mongodb,ef-fluent-api,C#,Entity Framework,Mongodb,Ef Fluent Api,我的域类如下所示: public class Author { public int Id { get; set; } public string Name { get; set; } public IList<Post> Posts { get; set; } } public class Blog { public int Id { get; set; } public string Name { get; set; } publ

我的域类如下所示:

public class Author
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<Post> Posts { get; set; }
}

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<Post> Posts { get; set; }
}

public class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public Author Author { get; set; }
    public Blog Blog { get; set; }        
}
公共类作者
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共IList Posts{get;set;}
}
公共类博客
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共IList Posts{get;set;}
}
公营职位
{
公共int Id{get;set;}
公共字符串标题{get;set;}
公共字符串内容{get;set;}
公共作者{get;set;}
公共博客Blog{get;set;}
}
正如您所看到的,我绝对没有实体框架注释的任何数据注释或属性,我使用实体框架fluentapi在另一个类中为每个类配置实体框架相关的注释。 现在我想用MangoDb替换实体框架

但在mongo db中,我需要在Id的列表中放置一个属性,如下所示:

public class Author
{
    [BsonElement("_id")]
    [BsonRepresentation(BsonType.ObjectId)]
    public int Id { get; set; }
    public string Name { get; set; }
    public IList<Post> Posts { get; set; }
}
公共类作者
{
[b单一元素(“_id”)]
[BsonRepresentation(BsonType.ObjectId)]
公共int Id{get;set;}
公共字符串名称{get;set;}
公共IList Posts{get;set;}
}

我的问题是,有没有办法在另一个类之外进行配置,不要像我们在实体框架的fluent api中使用的那样接触我的poco类

基本上,您可以同时使用EntityFramework和MongoDB驱动程序属性。但我不建议您使用EntityFramework中使用的完全相同的数据结构,因为SQL和NoSQL是完全不同的方法。使用NoSQL,您应该更多地考虑应用程序将如何使用数据和创建域,选择最佳嵌入策略并相应地应用索引

你可以在MongoDB网站上找到一些好的阅读资料。以下是一些要启动的链接:


您可以使用BsonClassMap类来实现这一点,如:

BsonClassMap.RegisterClassMap<Post>(cm => 
{ 
    cm.MapMember(x => x.Title).SetElementName("_title");
});
BsonClassMap.RegisterClassMap(cm=>
{ 
cm.MapMember(x=>x.Title).SetElementName(“_Title”);
});
文档在这里:

还有默认约定,对于Id字段,您不需要将其映射到_idname,它将自动处理。

好问题。如果我必须在代码中混合我的特定于实现的属性,我总是觉得很烦人。谢谢你的建议,但基本上数据的行为是一样的,我有一个博客,博客有一个作者和帖子。。。。。。我的问题是找到一种在类之外设置mongodb相关属性的方法。就像我们在使用fluentApiDo创建模型时使用entityframework一样,我需要在IMongoCollection中或在该类的其他位置设置RegisterClassMap的结果?@ViniciusGualberto不确定我是否正确理解您的意思。如果要应用此映射,只需将代码的映射块写入任意位置即可。通常在应用程序启动时完成。