[英]Entity Framework how do I INSERT unique value on many to many relationship without having to do manual check
有誰知道如何插入唯一值而無需顯式檢查現有值?
我能夠做到這一點,但是我對必須編寫的代碼印象深刻。 基本上,我創建了一個輔助函數來檢查容器上的唯一值。
該結構非常基本。
[條目] * <-----> * [UniqueValue]
主要代號
public static void ImportStuff ()
{
//Generate a list of importable items
List<DtoItems> items = DtoItemGetter.GetItems();
using( var container = new MyEntities() )
{
foreach( var item in items )
{
Entry newEntry = CreateNewEntry( item );
//********
// Here's the call to my helper method to check
// for the uniqueness of the values on the item I am importing
//********
item.UniqueValuesList.ForEach(
uv => HelperMethod( container, newEntry, uv ) );
containter.AddToEntries( newEntry );
//Less important... but it would be nice if I didn't
// have to save everytime I add an new entry... but
// this necessary for the Helper check.
container.SaveChanges();
}
}
}
輔助方法
public static void HelperMethod(
MyEntities container, Entry newEntry, string checkValue )
{
UniqueItem unique = null;
//Have to check to see if it already exists in the DB
container.uniqueItems.ForEach( uv => {
if( uv.Name == checkValue )
{
unique = uv;
} } );
//Here's the money, either add the one I found, or
//create a new one... meh
newEntry.UniqueItems.Add(
unique ?? new UniqueItem { Name = checkValue } );
}
希望這有足夠的道理。
實體框架尚不支持唯一約束-http: //blogs.msdn.com/b/efdesign/archive/2011/03/09/unique-constraints-in-the-entity-framework.aspx
因此,如果要使用唯一約束,則應在數據庫上手動設置約束並手動檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.