问题
Using EF5 Fluent API does anyone know if it's possible to have a binary column in the database but a long in the C#? When we put a long in the entity we always end up with EF errors at runtime (unable to perform the mapping). If we put a byte[] then everything works (binary in db usually means byte[] type in .NET code). We can't change database column type so it's not a solution.
Here is what we end up doing :
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()
})
If we were able to specify in the entity that CityId is a long (and not a byte[]) and the same for DbId then we wouldn't have to do all this redondant code. Therefore this is not possible, EF complains at runtime (because the db column type is binary). But SQL Server handles implicit conversions from binary to bigint...
回答1:
You can just use 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);
}
EDIT:
Okay, I've understand your problem. What you need is a Fluent API that does automatic conversion of byte[]
to long
and vice-versa for you. Unfortunately, Fluent API cannot do conversions for you.
But fortunately, you can have a wrapper property representing that byte[]
(binary) property which is just for your C# code's use. You just have to mark this wrapper property as [NotMapped]
in order for it not be part of your DB schema. Then you just have to use that wrapper property every time you need to modify this binary data.
Here's an example;
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);
}
}
}
}
Then you can use that wrapper by:
using(var ctx = new UsersContext())
{
SomeEntity s = new SomeEntity();
s.SomeByteWrapper = 123861234123;
ctx.SomeEntities.Add(s);
ctx.SaveChanges();
}
来源:https://stackoverflow.com/questions/17038334/ef5-fluent-api-byte-array-to-long