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