简体   繁体   English

实体框架-按ID搜索

[英]Entity Framework - Searching by ID

I have a table called Products and a table called ProductDescription. 我有一个名为Products的表和一个名为ProductDescription的表。 The ProductDescription has a primary key called ProductDescriptionID. ProductDescription有一个主键,称为ProductDescriptionID。 So, to get the description of a product I need to access both tables. 因此,要获取产品说明,我需要访问两个表。

Here is my code to access the description of a product but I don't know how to fix it, as I'm getting: "Cannot convert lambda expression to string because it is not a delegate type". 这是我访问产品描述的代码,但由于要获取,我不知道如何解决它:“由于不是委托类型,所以无法将lambda表达式转换为字符串”。

        productDetailsVM.ProductDescription = db.ProductDescriptions
            .Where(c => c.ProductDescriptionID.Any(p => p.ProductID == id))
            .FirstOrDefault();

Edit: 编辑:

    public partial class Product
    {    
        public int ProductID { get; set; }
        etc
    }

    public partial class ProductDescription
    {
        public int ProductDescriptionID { get; set; }

        public string Description { get; set; }
    }

How do I actually write this query? 我实际上如何编写此查询?

在此处输入图片说明在此处输入图片说明

I'm guessing your database is probably new and still in the works, you have yet to defined the relationship between Product and ProductDescription (a foreign key of ProductID in the ProductDescription table). 我猜您的数据库可能是新数据库,并且仍在使用中,您尚未定义Product和ProductDescription(ProductDescription表中ProductID的外键)之间的关系。

Once you have that relationship set up and have refreshed your EF diagram (assuming your not using Code First) you will be able to do: 一旦建立了这种关系并刷新了EF图(假设您未使用Code First),您将能够执行以下操作:

 var productDescription = db.Product.FirstOrDefault(p=>p.ProductID == id).ProductDescription;

This assumes that a Product has only 1 ProductDescription. 假设一个产品只有1个ProductDescription。

Wont this do it? 这样会做吗?

 productDetailsVM.ProductDescription = db.ProductDescriptions
            .Where(c => c.ProductID == id)
            .FirstOrDefault();

Supposing that you want a product to have a single description you either have to add the ProductId field to ProductDescription table or the ProductDescriptionID field to the Product table. 假设您希望产品具有单个描述,则必须将ProductId字段添加到ProductDescription表中,或者将ProductDescriptionID字段添加到Product表中。 This is called Entity splitting, you can find a video of this approach here. 这称为实体拆分,您可以在此处找到有关此方法的视频

Supposing that you want a product to have multiple descriptions and description multiple products (many to many) you need a "Bridge Table" with just two fields (product and description ids) conforming the primary key of this bridge table, this way you will have in your model a (many to many) relation, again there is a detailed video here. 假设您希望一个产品具有多个描述,并且描述多个产品(许多),则需要一个“桥表”,其中只有两个字段(产品和描述ID)符合此桥表的主键,这样您就可以在您的模型中(多对多)关系,这里还有一个详细的视频 .

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

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