【问题标题】:EF5 Fluent API byte array to longEF5 Fluent API 字节数组长
【发布时间】:2013-06-11 07:07:20
【问题描述】:

使用 EF5 Fluent API 有谁知道是否可以在数据库中有一个二进制列但在 C# 中是否有一个 long 列?当我们在实体中放置一个 long 时,我们总是会在运行时出现 EF 错误(无法执行映射)。如果我们放置一个 byte[] 则一切正常(db 中的二进制通常意味着 .NET 代码中的 byte[] 类型)。我们无法更改数据库列类型,因此这不是解决方案。

这是我们最终要做的事情:

from l in LeadDataRepository.GetAll()
select new { // we need an anonymous type here we use Linq to Entities
    FirstName = l.FirstName,
    LastName = l.LastName,
    CompanyName = l.CompanyName,
    CityId = l.CityId,
    DbID = l.DbId
 }).ToList() // once listed we use Linq to objects
.Select(l => new LeadListingViewModel() { // our real class
    FirstName = l.FirstName,
    LastName = l.LastName,
    CompanyName = l.CompanyName,
    CityId = l.CityId.ToLong(), // here we use our extension method on byte[] which converts to long
    DbID = l.DbId.ToLong()
})

如果我们能够在实体中指定 CityId 是 long(而不是 byte[])并且对于 DbId 也是如此,那么我们就不必执行所有这些冗余代码。因此这是不可能的,EF 在运行时抱怨(因为 db 列类型是二进制的)。但是 SQL Server 处理从二进制到 bigint 的隐式转换...

【问题讨论】:

    标签: c# api entity-framework-5 fluent


    【解决方案1】:

    你可以使用BitConverter

    static void Main(string[] args)
    {
        long number = 1234167237613;
    
        //convert to byte array
        byte[] bytes = BitConverter.GetBytes(number);
    
        //vice-versa
        long number2 = BitConverter.ToInt64(bytes, 0);
    
        Console.WriteLine(number == number2);
    }
    

    编辑:

    好的,我明白你的问题了。您需要的是一个 Fluent API,它可以自动将 byte[] 转换为 long,反之亦然。很遗憾,Fluent API 无法为您进行转换。

    但幸运的是,您可以有一个包装器属性来表示 byte[](二进制)属性,该属性仅供您的 C# 代码使用。您只需将此包装器属性标记为[NotMapped],以便它不属于您的数据库模式。然后,您只需在每次需要修改此二进制数据时使用该包装器属性。

    这是一个例子;

    namespace EntityFrameworkByteToLong.Models
    {
        public class SomeEntity
        {
            public int Id { get; set; }
    
            public byte[] SomeBytes { get; set; } //this is the column in your DB that can't be changed
    
            [NotMapped]
            public long SomeByteWrapper //your wrapper obviously
            {
                get
                {
                    return BitConverter.ToInt64(SomeBytes, 0);
                }
                set
                {
                    SomeBytes = BitConverter.GetBytes(value);
                }
            }
        }
    }
    

    然后您可以通过以下方式使用该包装器:

            using(var ctx = new UsersContext())
            {
                SomeEntity s = new SomeEntity();
                s.SomeByteWrapper = 123861234123;
    
                ctx.SomeEntities.Add(s);
                ctx.SaveChanges();
            }
    

    【讨论】:

    • 您好,我们知道 Bitconverter,但不能在 Linq 查询中调用“标准”函数。为此,您需要首先使用匿名类型,列出它,然后投影到正确的类型
    • 您要转换为 long 的 byte[] 属性在哪里?
    • 我明白了,您在问如何使用 Fluent API 自动完成这项工作?是吗?
    • 没错。因为目前我们最终会编写大量冗余代码
    • 完全符合我的需求!非常感谢@aiaptag
    猜你喜欢
    • 2012-12-01
    • 2013-04-23
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多