我有一個相當簡單的場景,我似乎無法獲得正確的邏輯。我正在使用POCO的WCF服務來讀取和寫入數據到數據庫。我有一個關鍵字表有一個外鍵UserID鏈接到UserProfile表。我正在添加和修改關鍵字集合,但是當我嘗試在GetKeywords方法中包含UserProfile,然後進行一些更改並調用StoreKeywords方法時,我遇到了參照完整性問題。如果我不包含UserProfiles,我可以添加和更新沒有問題。我使用了支持WCF的POCO生成器,並修改了T4以刪除虛擬並使用FixupCollections。使用WCF POCO的實體框架參照完整性問題
任何幫助將不勝感激。提前致謝。
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;
}
}
總是告訴哪裏(在哪一行代碼)發生異常。你在下面的評論中提到的例外。 –
異常發生在context.Keywords.Attach(kw);但它是由於GetKeywords方法,包括UserProfile – MarcZ2121