简体   繁体   English

Linq to SQL属性映射到表

[英]Linq to SQL property mapping to table

Let's say I have a database with 2 tables : User(Id, Name, PetId,...) and Pet(Id, Name, Color,...) and this class : 假设我有一个包含2个表的数据库:User(Id,Name,PetId,...)和Pet(Id,Name,Color,...)和此类:

class UserPet
{
 // User table, generated in dbml
 public User User {get;}

 // Pet table, generated in dbml
 public Pet Pet {get;}

public UserPet(User user, Pet pet)
{
 User = user;
 Pet = pet;
}
 [...]
}

I'm trying to make a link to sql method with a filter like 我正在尝试使用类似过滤器的方法链接到sql方法

public UserPet[] Get(Expression<Func<UserPet, bool>> criteria)
{
 [...]
// System.NotSupportedException: 'The member 'User' has not supported translation to sql'
 return (from user in context.User
        join pet in context.Pet on usr.PetId equal pet.Id
     -->   select new UserPet(user, pet).Where(criteria).ToArray()
}

So that, for instance, I can make query with dynamic filtering: 这样,例如,我可以使用动态过滤进行查询:

Get(userPet => userPet.Pet.Color == "Red" && userPet.User.Name == "Dave")

Here, the criteria is an object containing 2 tables and I am struggling to use it in the linq to sql method. 在这里,条件是一个包含2个表的对象,我正努力在linq to sql方法中使用它。 Any idea ? 任何想法 ? How to tell Linq To SQL that the properties of UserPet are the tables that were generated in the dbml ? 如何告诉Linq To SQL UserPet的属性是在dbml中生成的表?

Thanks ! 谢谢 !

After some time struggling, I found that the below modification worked (remove the constructor with parameter from UserPet). 经过一段时间的努力,我发现以下修改有效(从UserPet中删除带有参数的构造函数)。 Why ? 为什么呢 Mystery ! 神秘!

UserPet: 用户宠物:

class UserPet
{
 public User user {get;set;}
 public Pet pet {get;set}
}

And method : 和方法:

public UserPet[] Get(Expression<Func<UserPet, bool>> criteria)
{
 [...]
 return (from user in context.User
        join pet in context.Pet on usr.PetId equal pet.Id
        select new UserPet(){User = user, Pet = pet}).Where(criteria).ToArray()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM