简体   繁体   English

实体框架4中的部分映射

[英]Partial mapping in Entity Framework 4

I want to be able to do the following: 我希望能够执行以下操作:

I have a model and inside there I do have an entity. 我有一个模型,里面有一个实体。

This entity has the following structure: 该实体具有以下结构:

public class Client
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}   

What I want now, is to just get the client name based on the id. 我现在想要的只是根据ID获取客户端名称。 Therefore I wrote a stored procedure which is doing this. 因此,我编写了一个存储过程。

CREATE PROCEDURE [Client].[GetBasics]
@Id INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;


SELECT 
    Name
FROM Client.Client
INNER JOIN Client.Validity ON ClientId = Client.Id
WHERE
    Client.Id = @Id; 
 END

Now, going back to VS, I do update the model from the database with the stored procedure included. 现在,回到VS,我使用包含的存储过程从数据库中更新了模型。

Next step is to map this stored procedure to the client entity as a function import. 下一步是将此存储过程作为函数导入映射到客户端实体。

This also works fine. 这也很好。

Trying now to load one client's name results into an error during runtime... 现在尝试在运行时加载一个客户端名称会导致错误...

"The data reader is incompatible with the specified 'CSTestModel.Client'. A member of the type, 'Id', does not have a corresponding column in the data reader with the same name." “数据读取器与指定的'CSTestModel.Client'不兼容。类型'Id'的成员在数据读取器中没有具有相同名称的对应列。”

I am OK with the message. 我可以接受此消息。 I know how to fix this (returning as result set Id, Name, Description). 我知道如何解决此问题(返回结果集ID,名称,描述)。

My idea behind this question is the following: 我对这个问题的看法如下:

I just want to load parts of the entity, not the complete entity itself. 我只想加载实体的一部分,而不是整个实体本身。 I have a restriction here to just use stored procedures for the entire communication towards/from the database. 我在这里有一个限制,即只能使用存储过程来往/从数据库进行整个通信。

Is there a solution to my problem (except creating complex types, LINQ on the result set itself)? 有没有解决我的问题的方法(除了创建复杂类型,结果集本身上的LINQ)? And if yes, can someone point me to the right direction? 如果是的话,有人可以指出我正确的方向吗?

Many thanks, 非常感谢,

Dimi 迪米

Just project onto a POCO: 只需投影到POCO上:

var q = from c in Context.Clients
        select new NameOnlyPresentation
                   {
                       Id = c.Id,
                       Name = c.Name
                   };

... or just the name: ...或只是名称:

public string ClientName(int id)
{
    return (from c in Context.Clients
            where c.Id == id
            select c.Name).FirstOrDefault();
}

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

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