我有windows phone 8本地数据库的问题。这就是我的数据库代码的外观:
[Table(Name = "Folders")]
public class FolderTable : INotifyPropertyChanged, INotifyPropertyChanging, IEqualityComparer<FolderTable>
{
private string _folderName;
private string _description;
private string _password;
private string _tileColorName;
[Column(IsPrimaryKey = true)]
public string FolderName
{
get { return _folderName; }
set
{
if (_folderName != value)
{
NotifyPropertyChanging();
_folderName = value;
NotifyPropertyChanged();
}
}
}
[Column(CanBeNull = false)]
public string Description
{
get { return _description; }
set
{
if (_description != value)
{
NotifyPropertyChanging();
_description = value;
NotifyPropertyChanged();
}
}
}
[Column]
public string Password
{
get { return _password; }
set
{
if (_password != value)
{
NotifyPropertyChanging();
_password = value;
NotifyPropertyChanged();
}
}
}
[Column]
public string TileColorName
{
get { return _tileColorName; }
set
{
if (_tileColorName != value)
{
NotifyPropertyChanging();
_tileColorName = value;
NotifyPropertyChanged();
}
}
}
private void NotifyPropertyChanging([CallerMemberName] string propertyName = "")
{
if ( PropertyChanging != null)
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if ( PropertyChanged != null )
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
public event PropertyChangingEventHandler PropertyChanging;
public bool Equals(FolderTable x, FolderTable y)
{
return x.FolderName == y.FolderName;
}
public int GetHashCode(FolderTable obj)
{
return obj.FolderName.GetHashCode();
}
}
文件夹添加:
public Task Add(Folder folder)
{
var folderTable = GetFolderTable(folder);
_databaseContext.Folders.InsertOnSubmit(folderTable);
return Task.FromResult(true);
}
提交:
public Task Commit()
{
try
{
_databaseContext.Folders.Context.SubmitChanges();
}
catch (DuplicateKeyException duplicateKeyException)
{
_databaseContext.Dispose();
_databaseContext = new FolderDbContext(FolderDbContext.DBConnectionString);
throw new FolderAlreadyExistsException(duplicateKeyException);
}
return Task.FromResult(true);
}
当我Add
新文件夹(之前不存在具有此类名称的文件夹),Commit
然后我尝试添加具有相同名称DuplicateKeyException
的文件夹时,将被抛出并正确处理。但是,在catch部分重新创建上下文后,下一次调用具有相同名称的Add和Commit文件夹会抛出SqlCeException
消息:"A duplicate value cannot be inserted into a unique index. [ Table name = Folders,Constraint name = PK_Folders ]"
。这是正常的行为还是我做错了什么?在什么情况下抛出DuplicateKeyException
?如何抓住SqlCeException
?我甚至看不到System.Data.SqlServerCe
名称空间。
答案 0 :(得分:1)
如果您希望明确捕获SqlCeException,请使用反射来获取示例的类型名称:
ex.GetType().Name == "SqlCeException"