【问题标题】:Refreshing or disposing and recreating EF DB刷新或处理和重新创建 EF DB
【发布时间】:2017-10-06 20:36:51
【问题描述】:

所以我正在使用实体框架、c# 和 Azure 创建一个简单的消息传递应用程序。这是我的架构。

public class UserContext : DbContext {
    public UserContext() : base("name=Official") {

    }
    public DbSet<User> Users { get; set; }
    public DbSet<Message> Messages { get; set; }
}

public class User {
    [Key]
    public string username { get; set; }
    public string password { get; set; }
    //public int test { get; set; }

    public virtual ICollection<User> friends { get; set; }

    public virtual ICollection<Message> SentMessages { get; set; }
    public virtual ICollection<Message> ReceivedMessages { get; set; }

    public static implicit operator User(bool v) {
        throw new NotImplementedException();
    }

    public override string ToString() {
        return username;
    }
}

public class Message {
    [Key]
    public int ID { get; set; }

    public virtual User sender { get; set; }
    public virtual User recipient { get; set; }
    public virtual Group group { get; set; }

    public string content { get; set; }

    public int TimeSent { get; set; }
}

public class Group {
    [Key]
    public int ID { get; set; }

    public virtual ICollection<User> members { get; set; }
    public virtual ICollection<Message> messages { get; set; }
}

我的数据库在 UniversalStuff 类中声明过一次,我可以在整个程序的任何地方访问它。

public static UserContext db = new UserContext();

所以我有一个对话表单,它基本上是主屏幕,它看起来像这样:

我遇到的问题是找到一种方法来更新程序,以便在程序运行时发送给您的新消息显示在右侧的文本框中。

每当用户更改右侧列表框中的选定项目(甚至单击空白处)时,我都会通过处理和重新创建 DB 对象来“解决”它。显然这不是最好的方法,现在我想实现系统托盘通知,所以如果程序被最小化到任务栏,你可以看到你是否收到了新的通知。

现在,关于问题: 在用户无需执行任何操作的情况下弹出新消息的最佳方式是什么?

【问题讨论】:

  • 您可以使用 SignalR,支持 AFAIK WinForms/WPF。
  • @maccettura 现在正在调查。
  • 我认为@maccettura 建议的一些中间层是首选,但如果您不能或不愿意使用它,您可以考虑在 EF 中映射 SQLDependency。见:code.msdn.microsoft.com/How-to-use-SqlDependency-5c0da0b3

标签: c# sql multithreading visual-studio entity-framework


【解决方案1】:

你可以使用定时器https://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspxhttps://docs.microsoft.com/en-us/dotnet/framework/winforms/controls/timer-component-windows-forms
并且在基于您选择的时间间隔的计时器滴答声中,您可以检查数据库并获取添加的最新记录并显示它。

例如:https://stackoverflow.com/a/23137100/20126

您也可以使用 SqlDependency https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/detecting-changes-with-sqldependency,这对我来说效果不佳(可能只是我正在研究的情况)。

【讨论】:

    猜你喜欢
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2015-01-18
    相关资源
    最近更新 更多