C# 如何为2个字段创建索引以使其在集合中唯一

C# 如何为2个字段创建索引以使其在集合中唯一,c#,mongodb,asp.net-core,C#,Mongodb,Asp.net Core,我拥有bson配置的实体 [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } [BsonElement("Email")] public string Email { get; set; } [BsonElement("PhoneNumber")] public string PhoneNumber { get; set; } [BsonElement("Role")] public

我拥有bson配置的实体

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

[BsonElement("Email")]
public string Email { get; set; }

[BsonElement("PhoneNumber")]
public string PhoneNumber { get; set; }

[BsonElement("Role")]
public Role Role { get; set; }
在集合中,我希望有一对唯一的字段
Email
Role
。但是,如何在核心API中实现它,还不明白吗


我找到了属性
索引
,这个属性有
CreateOne
CreateMany
但是如何配置呢

一旦建立了连接等,并拥有
集合
对象

您将调用找到的索引键API()

collection.index.CreateOne(新的CreateIndexModel(新的IndexKeyDefinitionBuilder().Ascending(x=>x.Email).Ascending(x=>x.Role),新的CreateIndexOptions{})


您还可以使用文字名称,例如
“Email”
(如果您不想或不需要类型安全),当然可以使用
降序而不是
升序,并且可以省略或使用
CreateIndexOptions
(听起来您希望
Unique=true

您将调用找到的索引键API()

collection.index.CreateOne(新的CreateIndexModel(新的IndexKeyDefinitionBuilder().Ascending(x=>x.Email).Ascending(x=>x.Role),新的CreateIndexOptions{})

您还可以使用文字名称,例如
“Email”
(如果您不想或不需要类型安全),当然可以使用
降序而不是
升序,并且可以省略或使用
CreateIndexOptions
(听起来您希望
Unique=true