Search code examples
c#.netentity-framework-6

Entity Framework 6 How to Map a UserDefined datatype property as varchar type column in DB


I have to map a Userdefined type Property as a Varchar Column Using EntityFramework 6. So I have an entity called EngineQuota :

'''

 [Table(EngineQuotas)]
    public partial class EngineQuota
    {
        public int Id { get; set; }
        
        public DecimalList Quotas { get; set; }

        public int? EngineId { get; set; }    

        private EngineQuotas()
        {
            this.Quotas = new DecimalList();
        }
    }

'''

The DecimalList is a seperate class which holds a sortedList of decimals '''

public class DecimalList : IEnumerable<decimal>
    {
        private readonly SortedSet<decimal> items;

        public DecimalList()
        {
            this.items = new SortedSet<decimal>();
        }

        public IEnumerator<decimal> GetEnumerator()
        {
            return this.items.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
 public override string ToString()
    {
        return string.Join(",", this.items.Select(n => n.ToString()).ToArray());             
    }
       
    }
}

''' In DB I want a comma seperated value of items in DecimalList to be stored in a Column Quota in Table EngineQuotas. How is this possible in Entity Framework6 . Tried Using ComplexType but not able to get some result

Edited For Awnser: As suggested by Quain. I created another property

  1. public DecimalList DecimalListQuotas { get; set; } and Changed the Quotas property to type string to matchup with DB . The Quotas property is now using DecimalListQuotas internally for get set
e public string Quotas
    {
        get
        {
            return DecimalListQuotas.ToString();
        }
        private set
        {
            decimal[] nums = value.Split(',').Select(decimal.Parse).ToArray();
            this.DecimalListQuotas.AddRange(nums);
        }

    }










                                             

Solution

  • Take a look at EF custom converters - this should solve it.
    One thing - if you are converting collection, than it's possible, that You will need to provide custom comparer in this entity's configuration, because it is possible, that change tracker wont detect collection update.

    EDIT: For EF6 you could try this.