我在我的應用程序中有這個錯誤,我不知道如何解決。數據庫插入問題
我有5個表:
Customer
Branch
PointOfSale
User
CustomerEndUser
具有以下關係:
Customer->Branch one-to-many
Branch->PointOfSale one-to-many
Customer->CustomerEndUser one-to-many
User->CustomerEndUser one-to-one
PointOfSale->CustomerEndUser one-to-many
我使用ADO.NET實體框架來完成數據庫事務。
當我想添加一個新的CustomerEndUser時,我必須給它一個PointOfSale,一個用戶和一個Customer。但每次我調用CustomerEndUser的Insert方法時,該方法拋出一個異常:「'idenTTsystemEntities.PointOfSaleSet'中的實體參與'FK_PointsOfSale_Branches'關係,發現0個相關的'分支'1'Branches'expected。管理員會收到通知,請稍後再試。「,即使我向CustomerEndUser提供了所需的信息。
這是我在Insert方法使用的代碼:
public static CustomerEndUser InsertIntUser(CustomerEndUser endUser)
{
idenTTsystemEntities context = new idenTTsystemEntities();
var mbr = Membership.Providers[INTMembershipProviderName];
MembershipCreateStatus userStatus;
if(mbr==null)
{
throw new NullReferenceException("Membership Provider is null");
}
MembershipUser mbrUser = mbr.CreateUser(endUser.Username, endUser.Password, endUser.Email, "no question",
"no answer", true, Guid.NewGuid(),
out userStatus);
if(userStatus==MembershipCreateStatus.Success)
{
ProfileBase profileBase = ProfileBase.Create(endUser.Username);
SettingsPropertyValueCollection profileProperties =
profileBase.Providers[INTProfileProviderName].GetPropertyValues(profileBase.Context,
ProfileBase.Properties);
//add the firstname, lastname and dateofbirth properties
profileProperties["FirstName"].PropertyValue = endUser.FirstName;
profileProperties["LastName"].PropertyValue = endUser.LastName;
var shortDate = new System.Globalization.DateTimeFormatInfo();
shortDate.ShortDatePattern = "dd.MM.yyyy";
profileProperties["DateOfBirth"].PropertyValue = Convert.ToDateTime(endUser.BirthDate, shortDate);
//get the id of the newly created end user
Guid newUserId = (Guid)mbrUser.ProviderUserKey;
//add the user to the CustomerEndUser
User newUser = context.UserSet.Where(u => u.UserId == newUserId).First();
endUser.User = newUser;
//get the customer to which the end user belongs to
Customer cust = context.CustomerSet.Where(c => c.CustomerId == CustomerId).First();
endUser.Customer = cust;
//get the pos selected in the insertform
Guid posId = endUser.PosId;
PointOfSale selectedPos = context.PointOfSaleSet.Include("Branch").Where(br => br.PointOfSaleId == posId).First();
endUser.PointOfSale = selectedPos;
endUser.EndUserId = Guid.NewGuid();
context.AddToCustomerEndUsers(endUser);
profileProperties["Language"].PropertyValue = "de-DE";
profileBase.Providers[INTProfileProviderName].SetPropertyValues(profileBase.Context, profileProperties);
profileBase.Save();
context.SaveChanges();
return endUser;
}
throw new MembershipCreateUserException(userStatus);
}
谷歌說,這可以通過使用存儲過程是固定的,但我想如果可能的不同的解決方案。謝謝!
乾杯, 亞歷巴拉克
'.INCLUDE( 「分公司」)' 中的 'selectedPos' 的定義就是這樣做的。當我檢查'selectedPos'的內容時,它內部有一個分支,但是同樣的異常被拋出。我不確定這個異常是否與客戶有關。 –