他喵的又在搞飛機了..=ω=a
原文網址:http://blog.udn.com/andy840119/118612814
列印日期:2026/02/11
[解決]使用ICollection中出現 No field was found backing property of entity type.
2018/10/25 18:38:08

前言 : 


有時候Domain物件裡面有List物件時,習慣寫成這樣


public class ShopopingCart : BaseEntity


{


    private ICollection<Product> _products; 


    public virtual ICollection<Product> Products


    {


        get => _products ?? (_products = new List<Product>());


        set => _products = value;


    }


}


之後在存取物件時,就不用擔心這個物件會不會是null的狀態


.



然後寫著寫著很衰洨的不知道未啥遇到這個錯誤


System.InvalidOperationException: No field was found backing property Product of entity type ShopopingCart. Lazy-loaded navigation properties must have backing fields. Either name the backing field so that it is picked up by convention or configure the backing field to use.


.




正文 : 


後來找了一下,發現了一篇很有趣的回復


https://github.com/aspnet/EntityFrameworkCore/issues/12885#issuecomment-410712486



.


簡單來說,public virtual ICollection<T> 的命名要和private ICollection<T>的一樣


.



像上面這個寫法


public 的變數有加s


但private的忘了加


就會產生錯誤


.





心得 : 


雞掰