簡體   English   中英

從與實體框架的對話中刪除用戶

[英]Deleting a User from a Conversation with Entity Framework

我有一個“ Conversation表,其中有“ Users列表作為一列,以及“ Messages列表和一些其他數據。

我期待刪除 UserConversation表,而不刪除UserConversation完全,因為他們可能在別處使用。

我不確定該怎么做...

我希望使用Linq查詢來執行此操作,但是嘗試創建查詢一直沒有成功。

任何幫助將非常感激!

[HttpPut]
//[ResponseType(typeof(Conversation))]
public async Task<IHttpActionResult> RemoveUserFromGroup(String key, User user)
{
    Conversation conver = await db.Conversations.FindAsync(key);

    if (conver == null)
    {
            return NotFound();
    }

    IEnumerable<User> del = from d in conver.Users
                            where d.Email == user.Email
                            select d;

    conver.Users.Remove(del);    // ERROR ON THIS LINE AT "del"

    await db.SaveChangesAsync();

    return Ok(conver);
}

這段代碼並沒有實現我想要的功能

Conversation課程:

[DataContract]
public class Conversation
{
    [Key]
    [DataMember]
    public string Key { get; set; }

    [DataMember]
    public string ConversationName { get; set; }

    [DataMember]
    public string Administrator { get; set; }

    [DataMember]
    public virtual ICollection<User> Users { get; set; }

    [DataMember]
    public virtual ICollection<Message> Messages { get; set; }

    public Conversation()
    {
        Users = new HashSet<User>();
    }
}

User類別:

[DataContract]
public class User
{
    [Key]
    [DataMember]
    public string Email { get; set; }

    [DataMember]
    public string Password { get; set; }

    [DataMember]
    public bool Admin { get; set; }

    [DataMember]
    public virtual ICollection<Conversation> Conversations { get; set; }

    public User()
    {
        Conversations = new HashSet<Conversation>();
    }
}
[HttpPut]
public async Task<IHttpActionResult> RemoveUserFromGroup(String key, [FromBody]User user)
{
    Conversation conver = await db.Conversations.FindAsync(key);
    if (conver == null)
    {
          return NotFound();
    }

    IEnumerable<User> del = from d in conver.Users
                            where d.Email == user.Email
                            select d;

    conver.Users.Remove(del.ToList()[0]);

    await db.SaveChangesAsync();
    return Ok(conver);
}

此解決方案解決了該問題! 它將適當地從指定組中的指定用戶中刪除用戶。

暫無
暫無

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

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