簡體   English   中英

使用C#更新mongoDB中的查詢

[英]Update a query in mongoDB with c#

X變量中的編譯器錯誤CS1061,我想更新mongodb中的查詢,但問題是引發了x的錯誤。

public async Task<string> Update(string id, TEntity user)
    {
        await collection.ReplaceOneAsync(x => x.id == id, user);
        return "";
    }

在此代碼中: ReplaceOneAsync(x => x.id == id, user) xTEntity類型。

該錯誤表明,從編譯器的角度來看, TEntity不包含屬性id

解決它的一種方法是定義每個TEntity必須繼承的抽象:

public interface IEntity
{
   string id { get; set; }
}

然后在存儲庫類中(根據您發布的方法,我假設它是TEntity的通用存儲庫類),在TEntity上添加通用約束,如下所示:

public class MyRepository<TEntity> where TEntity : IEntity
{
    // collection should be IMongoCollection<TEntity> 
    private IMongoCollection<TEntity> collection; // initialized elsewhere

    public async Task<string> Update(string id, TEntity user)
    {
        await collection.ReplaceOneAsync(x => x.id == id, user);
        return "";
    }

    // ...other members...
}

由於我們where TEntity : IEntity包括了通用約束,因此編譯器現在知道每個TEntity都有一個string id屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM