Constrain the number of child entities in Entity Framework

前端 未结 2 1093
渐次进展
渐次进展 2021-01-26 20:25

Bottom Line Up Front

Is there a succinct way that I can constrain the number of child entities that can belong to a parent in Entity Framework. I am using 4.3.1 at th

2条回答
  •  情歌与酒
    2021-01-26 21:05

    There is no built-in way so you will have to code such validation yourselves. Some quick ideas:

    • You can for example use custom collection for the navigation property which will fire exception when you try to add additional search exceeding the threshold. It is simple but it demands you to have all searches loaded, it will have concurrency problems and moreover it can fire during loading search list and searches from database.
    • You can handle it in overriden SaveChanges. You will at least have to check how many searches are already related to search list but you will still have concurrency problem (what if other request tries to add search to the same list but only one place is remaining - both can succeed the check and insert related search)
    • You can handle it in database trigger - again it will have concurrency problems

    Avoiding concurrency problems completely requires hand written queries with locking hints to ensure that only one request can check number of searches per search list and insert a new search in atomic transaction.

提交回复
热议问题