Base solution for your next web application
Starts in:
01 DAYS
01 HRS
01 MIN
01 SEC
Open Closed

HowTo: use read only entities for db enums via repositories #1504


User avatar
0
sergii created

Could someone say what is best practice to work with enums like AddressType, Country so on but stored on DB side ? Should I load them every time via repository before I want to assign them ?

// app service code
var newOffice1  = new Office () {Name="Some Name", TypeId=officeDto.TypeId   }
officeRepository.Insert(newOffice1 );
// or ?
var newOffice2  = new Office () {Name="Some Name", Type=officeRepository.Get(officeDto.TypeId)  }
officeRepository.Insert(newOffice2 );

//
// domain code
public class Office :  Entity<int>
{
        public virtual string Name { get; set; }

        public virtual int TypeId { get; set; }
        [ForeignKey("TypeId")]
        public virtual OfficeType OfficeType { get; set; }
}

// read only,  can't be added or updated, with coded conversion by ID to c# enum
public class OfficeType :  Entity<int>
{
        public virtual string Name { get; set; }
        public virtual string Description{ get; set; }
}

1 Answer(s)
  • User Avatar
    0
    hikalkan created
    Support Team

    You can use the first approach since it does not query from database for office. If given officeid is invalid, then databse will throw exception because of foreign key restriction. For such enums, I also suggest to use caching them. You can use EntityCache class: <a class="postlink" href="http://www.aspnetboilerplate.com/Pages/Documents/Caching#entity-caching">http://www.aspnetboilerplate.com/Pages/ ... ty-caching</a>