Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a struct in place of a primitive for a EF4 property type

I've got an EF4 entity (code-first) that includes an int bitmask. I've created a Bitmask struct to make working with bitmasks easier (provides bool properties to access the bits). The bitmask struct includes overloaded implicit operators for converting to and from an int.

I tried setting the property type to the bitmask struct but the value is coming back as 0. I know the value in the database has a value and the bitmask works in my unit tests. I set the HasColumnType to "INT".

The property...

[Required]
[Display(Name = "Display Pages Bitmask")]
[Column(Name = "fDisplayPagesBitmask")]
public DisplayPagesBitmask DisplayPagesBitmask { get; set; }

From the context object...

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Website>()
        .Property(m => m.DisplayPagesBitmask)
        .HasColumnType("INT");
}

Is this possible? If so, what do I need to do to get it to work?

like image 534
Brian Avatar asked Jan 13 '11 01:01

Brian


1 Answers

You can't map your structure directly. You have to map int property (make setter internal or protected) and provide second non mapped property (use NotMappedAttribute or Ignore method) of your custom type which internally sets mapped integer property.

like image 162
Ladislav Mrnka Avatar answered Dec 18 '22 18:12

Ladislav Mrnka