1
我正在創建一個簡單的Windows Phone 8應用程序。要在本地存儲數據,我正在使用Microsoft的ORM LINQ TO SQL。我假設它使用Microsoft Server提供的本地數據庫SQL Server CE。我已經定義了一張存儲州和首府名稱的表格。SQL Server CE中的每個表都必須有主鍵嗎?
[Table]
public class State : INotifyPropertyChanged, INotifyPropertyChanging
{
private string _name;
public State(string name, string capital)
{
this.Name = name;
this.Capital = capital;
}
[Column]
public string Name
{
get
{
return _name;
}
set
{
if (_name != value)
{
NotifyPropertyChanging("Name");
_name = value;
NotifyPropertyChanged("Name");
}
}
}
private string _capital;
[Column]
public string Capital
{
get
{
return _capital;
}
set
{
if (_capital != value)
{
NotifyPropertyChanging("Capital");
_capital = value;
NotifyPropertyChanged("Capital");
}
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
// Used to notify the page that a data context property changed
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
#region INotifyPropertyChanging Members
public event PropertyChangingEventHandler PropertyChanging;
// Used to notify the data context that a data context property is about to change
private void NotifyPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
{
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
}
#endregion
}
我也定義了DataBase上下文類。
public class DbDataContext : DataContext
{
// Specify the connection string as a static, used in main page and app.xaml.
public static string DBConnectionString = "Data Source=isostore:/ToDo.sdf";
// Pass the connection string to the base class.
public DbDataContext(string connectionString): base(connectionString)
{
}
// Specify a single table for the to-do items.
public Table<State> State_table;
}
現在,當我嘗試在MainPage類的構造函數中插入一行,它拋出一個異常說「System.InvalidOperationException」。
public MainPage()
{
InitializeComponent();
State temp = new State("Maharashtra", "Mumbai");
dbobj = new DbDataContext(DbDataContext.DBConnectionString);
dbobj.State_table.InsertOnSubmit(temp); //This where it generates an exception
dbobj.SubmitChanges();
}
但是,當我在我的課「國家」重新定義「名稱」屬性爲
[Column(IsPrimaryKey = true)]
public string Name
然後它不拋出異常。 任何人都可以告訴我爲什麼這是happnening?
謝謝!
**任何關係數據庫中的每個表**應該有一個**主鍵** - 它必須有**的東西**讓你唯一可靠地識別每一行! – 2015-02-23 06:17:50
這就是RA理論在SQL中不存在的地方。在各種關係數據庫實現(例如SQL Server;非CE,無論如何)中都可能沒有任何CK(因此也沒有PK;形式或其他)的表。 。如何可以用這樣的RA操作是另一回事.. http://stackoverflow.com/questions/3459429/is-a-primary-key-necessary-in-sql-server(但這個問題問的是「需要「在標題中的」CE「中。此外,可能有一個或多個CK不是」PK「,但許多ORM在完全RA支持中是」啞「。) – user2864740 2015-02-23 06:19:00