EntityFramework数据库第一类-类型映射-将二进制(8)从SQL映射到C#中的int [英] EntityFramework database first - type mapping - map binary(8) from SQL to int in C#

查看:190
本文介绍了EntityFramework数据库第一类-类型映射-将二进制(8)从SQL映射到C#中的int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SQL内部,我有具有主键为binary(8)的表.当我使用Update Model from Database将该表添加到模型中时,我可以看到该列具有type = Binary

Inside SQL I have table that have primary key as binary(8). When I add that table to my model using Update Model from Database I can see that this column has type=Binary

,在C#中,该列为byte[].

我可以将该列映射到int吗?

Can I map that column to int?

我知道我可以在SQL中使用CAST创建视图:

I know I can create a view with CAST in SQL:

SELECT
    Client_Id,
    CAST(Client_Id AS INT) AS NewClient_Id,
    * /*other columns*/
FROM
    dbo.Clients

但这不是解决方案,因为我必须能够写,而不仅仅是从该表中读取.我知道我可以为插入创建存储过程,但是我想避免这种情况.

but this isn't a solution, because I must be able to write, not just read from that table. I know I can create stored procedure for inserts but I'd like to avoid that.

我是EntityFramewor 6.1.3.

I'm usinf EntityFramewor 6.1.3.

推荐答案

您有3种不同的解决方案

You have 3 different solutions

x存储过程,但您不希望使用它们.

x Stored procedures but you don't want them.

x向您的班级添加一个未映射的属性.关于此解决方案的最大问题是,您无法使用not mapping属性进行查询.您必须将所有数据读取到客户端,然后将条件应用于客户端的非映射属性(因此您的应用程序不可扩展).

x Add a not mapped property to your class. The biggest problem about this solution is that you can't make queries using the not mapped property. You have to read all the data to the client then apply the condition on the non mapped property on the client (so your app is not scalable).

[NotMapped]
public long LongClientId
{
    get { return BitConverter.ToInt64(this.ClientId, 0); }
    set { this.ClientId = BitConverter.GetBytes(value); }
}

此查询无效

context.MyDbSet.Where(m => m.LongClientId == 12).ToList();

您需要以这种方式进行更改

You need to change it in this way

context.MyDbSet.ToList().Where(m => m.LongClientId == 12);

此查询的结果是,您将所有表的记录(从dbms传输到您的应用程序)加载到一个列表中,而不是携带所需的记录.

The result of this query is that you load all table's records (transfer from dbms to your app) into a list than you take the one you need.

x创建一个视图(可能是索引视图)并使用INSTEAD OF触发器.

x Create a view (probably an indexed view) and use an INSTEAD OF trigger.

这篇关于EntityFramework数据库第一类-类型映射-将二进制(8)从SQL映射到C#中的int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆