我有一个相当简单的场景,我似乎无法获得正确的逻辑。我正在使用带有POCO的WCF服务来读取和写入数据库。我有一个关键字表,其外键UserID链接到UserProfile表。我正在添加和修改关键字集合但是当我尝试在GetKeywords方法中包含UserProfile然后进行一些更改并调用StoreKeywords方法时,我会得到参照完整性问题。如果我不包含UserProfiles,我可以添加和更新没有问题。我使用了支持WCF的POCO生成器并修改了T4以删除虚拟并使用FixupCollections。
非常感谢任何帮助。提前谢谢。
GetKeywords服务:
public class Service : IService
{
public List<Keyword> GetKeywords()
{
var context = new myDBEntities();
var query = from c in context.Keywords
.Include("UserProfile")
select c;
//var query = from c in context.Keywords.Take(100)
// select c;
return query.ToList();
}
调用GetKeywords的客户端代码进行了一些更改,然后调用StoreKeywords:
public partial class MainWindow : Window
{
ObservableCollection<Keyword> keylist;
public MainWindow()
{
InitializeComponent();
PopulateGrid();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
myServiceClient client = new myServiceClient();
List<Keyword> updates = new List<Keyword>();
foreach (Keyword keyword in keylist)
{
if (keyword.State == State.Added)
{
keyword.CreationDate = DateTime.Now;
updates.Add(keyword);
}
if (keyword.State == State.Modified)
{
keyword.EditDate = DateTime.Now;
if (keyword.IsVoid == false) keyword.VoidDate = null;
if (keyword.IsVoid == true) keyword.VoidDate = DateTime.Now;
updates.Add(keyword);
}
}
client.StoreKeywords(updates.ToArray());
foreach (var kw in keylist)
{
kw.State = State.Unchanged;
}
PopulateGrid();
gridControl1.RefreshData();
}
private void PopulateGrid()
{
myServiceClient client = new myServiceClient();
keylist = new ObservableCollection<Keyword>(client.GetKeywords());
gridControl1.ItemsSource = keylist;
}
StoreKeywords服务:
public string StoreKeywords(List<Keyword> keywords)
{
try
{
using (var context = new myDBEntities())
{
context.ContextOptions.LazyLoadingEnabled = false;
foreach (Keyword kw in keywords)
{
context.Keywords.Attach(kw);
context.ObjectStateManager.ChangeObjectState(kw, StateHelpers.GetEquivalentEntityState(kw.State));
}
context.SaveChanges();
return "";
}
}
catch (Exception ex)
{
return ex.Message;
}
}
答案 0 :(得分:0)
在搜索互联网后,我找到了我的问题here的答案,这对我来说根本不明显。问题出在GetKeyword()方法中,因为它试图跟踪合并。新的GetKeywords()方法:
public List<Keyword> GetKeywords()
{
var context = new InstanexDBEntities();
context.Keywords.MergeOption = MergeOption.NoTracking;
var query = from c in context.Keywords
.Include("UserProfile").Take(100)
select c;
return query.ToList();
}