2017-10-06 40 views
0

因此,我使用實體框架,c#和Azure創建了一個簡單的消息應用程序。這是我的模式。刷新或處理和重新創建EF DB

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; } 
} 

我的DB在UniversalStuff類中聲明過一次,我可以在整個程序中的任何地方訪問它。

public static UserContext db = new UserContext(); 

所以我有一個對話形式基本上是主屏幕,它看起來像這樣: enter image description here

我有是找到一種方法來更新程序中的問題,使新的消息說被髮送給你,而你的程序運行在右邊的文本框中顯示出來。

每次用戶更改右側列表框中的選定項目(甚至單擊空白)時,我都會通過處理和重新創建DB對象來「解決」它。顯然,這不是最好的方式來做到這一點,現在我想實現系統托盤通知,所以如果程序最小化到任務欄,你可以看到,如果你收到一個新的通知。

現在,在這個問題上: 沒有用戶必須做任何事情,有新的消息彈出的最佳方式是什麼?

+2

您可以使用SignalR,AFAIK支持WinForms/WPF。 – maccettura

+0

@maccettura展望現在。 – ktfjulien

+0

我認爲@maccettura建議的一些中間層是首選,但如果你不能或不願意使用它,你可以考慮在EF中映射SQLDependency。請參閱:https://code.msdn.microsoft.com/How-to-use-SqlDependency-5c0da0b3 –

回答

2

你可以使用一個定時器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這並沒對我很好地工作(可能只是我的情況我工作)。