C# EF5 Fluent API字节数组变长
使用EF5 Fluent API,有人知道数据库中是否可以有一个二进制列,而C#中是否可以有一个长列?当我们在实体中放入long时,我们总是在运行时出现EF错误(无法执行映射)。如果我们放置一个byte[],那么一切都可以工作(db中的二进制通常意味着.NET代码中的byte[]类型)。我们无法更改数据库列类型,因此它不是解决方案 以下是我们最终要做的事情:C# EF5 Fluent API字节数组变长,c#,api,entity-framework-5,fluent,C#,Api,Entity Framework 5,Fluent,使用EF5 Fluent API,有人知道数据库中是否可以有一个二进制列,而C#中是否可以有一个长列?当我们在实体中放入long时,我们总是在运行时出现EF错误(无法执行映射)。如果我们放置一个byte[],那么一切都可以工作(db中的二进制通常意味着.NET代码中的byte[]类型)。我们无法更改数据库列类型,因此它不是解决方案 以下是我们最终要做的事情: from l in LeadDataRepository.GetAll() select new { // we need an anon
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是长的(而不是字节[]),DbId也是长的,那么我们就不必执行所有这些冗余代码。因此这是不可能的,EF在运行时抱怨(因为db列类型是二进制的)。但是SQL Server处理从二进制到bigint的隐式转换…您可以使用
编辑:
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()
})
好的,我理解你的问题。您需要的是一个流畅的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自动完成这一操作?是吗?没错。因为现在我们写了很多有用的代码,这完全符合我的需要!非常感谢@aiapatag