![](/img/trans.png)
[英]EF SaveChanges method throws: The relationship could not be changed because one or more of the foreign-key properties is non-nullable
[英]Override SaveChanges method to set all non-nullable entity properties
我們的數據庫設置方式是,對於每個表,所有列都不允許空值。 使用實體框架添加新記錄時,為每個屬性設置一個值變得非常煩人。 基本上,我想避免這種情況:
var customer = new usr_Customer();
customer.CUSTNMBR = customerNumber != null ? customerNumber : string.Empty;
customer.MerchantID = merchant.MerchantId != null ? merchant.MerchantId : string.Empty;
customer.SupplyClubID = merchant.SupplyClub != null ? merchant.SupplyClub : string.Empty;
customer.Group01 = merchant.Group01 != null ? merchant.Group01 : string.Empty;
要解決此問題,我想覆蓋SaveChanges()方法,並為每個null屬性設置一個值。 這是我到目前為止:
public override int SaveChanges()
{
var changeSet = ChangeTracker.Entries();
if (changeSet != null)
{
foreach (var entry in changeSet.Where(c => c.State == EntityState.Added))
{
//If entity properties are null, set them to something.
}
}
return base.SaveChanges();
}
此時,我不確定如何繼續,因為我不太了解EF。 我知道string類型的每個實體屬性都需要設置為string.empty,並且對於int類型的每個實體屬性,都需要設置為0,依此類推。 這是否可行,更重要的是,用這種方法解決我的問題是否有意義? 提前致謝。
您可以直接在構造函數中執行此操作。
在實體框架中,實體類被定義為部分 。 您可以擴展它們並添加執行初始化的構造函數或工廠方法:
public partial class usr_Customer
{
public usr_Customer()
{
MerchantID = string.Empty;
}
}
編輯:我通過反射向您的代碼添加了屬性初始化:
public override int SaveChanges()
{
var changeSet = ChangeTracker.Entries();
if (changeSet != null)
{
foreach (var entry in changeSet.Where(c => c.State == EntityState.Added))
{
Type entityType = entry.GetType();
//Get all the properties
var properties = entityType.GetProperties();
foreach(var property in properties)
{
var value = property.GetValue(entry);
//If the property value is null, initialize with a default value
if(value == null)
{
//Get the default value of the property
var defaultValue = Activator.CreateInstance(property.PropertyType);
property.SetValue(defaultValue, entry, null);
}
}
}
}
return base.SaveChanges();
}
它應該工作,但也許,你應該處理像導航屬性這樣的“特殊”屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.