[英]How to validate if parent entity does not child entity in EF
Let's say I have one to many relationship table ( Ex User - Rent ) 假设我有一对多关系表(Ex User-Rent)
public class User
{
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public virtual ICollection<Rent> Rents { get; set; }
}
public class Rent
{
public Int64 VideoId { get; set; }
public Int64 UserId { get; set; }
public virtual User User{get; set;}
public int RentingLength { get; set; }
public int RentingCost { get; set; }
}
I want to delete a User
record. 我要删除User
记录。 Before that, I want to check whether User
has references to Rent
or not. 在此之前,我想检查User
是否具有对Rent
引用。
What I have is : 我所拥有的是:
context.Users.Include("Rents").ToList();
then check Rent
list is null or not. 然后检查Rent
清单是否为空。
Is there any better way to do that? 有什么更好的方法吗?
Thanks. 谢谢。
context.Users.Include("Rents").ToList();
will materialize your query, getting all users. 将具体化您的查询,吸引所有用户。 Best way should be context.Rent.Where(r => r.userId == DesiredUserId).Any()
. 最好的方法应该是context.Rent.Where(r => r.userId == DesiredUserId).Any()
。 If true
then user has rents. 如果为true
则用户有租金。
Use Any
like this to check if record exits 像这样使用Any
来检查记录是否退出
public bool Exists(int YourUserId)
{
dbcontext.Rent.Any(e => e.UserId == YourUserId);
}
You are using Virtual keyword in navigational properties which means Rents will automatically be included in your query of Users. 您在导航属性中使用Virtual关键字,这意味着租金将自动包含在您的用户查询中。 So you don't need the Include Explicitly. 因此,您不需要明确包含。
So you can just do 所以你可以做
context.Users.Find(Id)
And it will include Rent as well for the user with primary key id 并且还将为具有主键ID的用户包括租金
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.