簡體   English   中英

沒有導航屬性的EF更新實體

[英]EF update entity without navigation properties

我具有以下實體及其關系。

public class User {
    [Key]
    public int UserId {get;set;}

    ...
}


public class Profile {
    [Key]
    public int ProfileId {get;set;}

    [Required]
    public virtual User User {get;set;}
}

現在,當我想更新Profile時,我通過ProfileId檢索它,應用更改,然后調用SaveChanges()

問題是EF抱怨屬性User是必需的。 我了解到,檢索Profile時EF不會加載它。

但是,如何更新個人資料而不影響或加載用戶呢?

另請注意,我使用的是通用存儲庫模式,並且希望在我的Repository<T>有一個方法告訴EF如果可能的話忽略任何給定的屬性。

類似於MyRepository<T>.IgnorePropertyForUpdate(T entity, ??? property )

謝謝高級。

問題是您沒有用戶的Poco可訪問FKid,而EF知道需要用戶。 您尚未提供記錄。 如果聲明了外鍵ID,即userId,則保存時將具有ID。 EF可以處理整個記錄並不存在的事實,只要有密鑰即可。

public class Profile {
[Key]
public int ProfileId {get;set;}


[Required]
[ForeignKey("User")] 
Public int UserId {get;set} 


public virtual User User {get;set;}
}

必需的批注會在保存更改之前檢查是否必須加載用戶。這是數據庫中的約束( 數據庫表Profile-> Column(User)allow null = false ),因此您必須將用戶包括在以下位置的Profile實體中例如,如果您正在使用Daynmic庫MyUserRepository.Include("User");

如果您直接這樣做,則可以這樣:

context.Prfiles.Include(p => p.User)....ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM