6

I am using ASP.NET MVC5 and MS SQL 2008 and EntityFramework 6, in my application i have a class Experiences that will allow the clients to add details of their experiences from period till period:

public class Experience
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Company { get; set; }
    public string FromDate { get; set; }
    public string ToDate { get; set; }
    public string Description { get; set; }
}

the FromDate format will be MMM yyyy, example Jan 2009, Oct 2010 , ...etc the ToDate format will be either MMM yyyy or Present and should be greater than or equal the FromDate value for example:

  1. From = Jan 2010, To= Oct 2014 ==> Accepted
  2. From = Jan 2010, To= Present ==> Accepted
  3. From = Oct 2014, To = Jul 2014 ==> Rejected the value to To Date should be greater than the From date

I made the class Period as follow

public class Period: IComparable
{
    public Period()
    {
         this.Month="Present";
    }

    public Period(string Month,int Year)
    {
        this.Month=Month;
        this.Year=Year;
    }

    public int CompareTo(object obj)
    {
        if(obj==null)
            return 1;
        Period period = obj as Period;
        if (period != null) 
        {
            if(this.Month=="Present" && period.Month=="Present")
                return 0;
            else if(period.Month=="Present")
                return -1;
            else if(this.Month=="Present")
                return 1;
            else
            {
                DateTime date;
                DateTime periodDate;
                if(!DateTime.TryParse(string.Format("01 {0} {1}",Month,Year),out date))
                    throw new ArgumentException("Instance is not a valid Period!");             
                if(!DateTime.TryParse(string.Format("01 {0} {1}",period.Month,period.Year),out periodDate))
                    throw new ArgumentException("Object is not a valid Period!");
                return date.Date.CompareTo(periodDate.Date);
            }
        }
           else 
              throw new ArgumentException("Object is not a Period");
    }

    public override int GetHashCode()
    {
        if(this==null)
            return 0;
        else
        {
            DateTime date;
            if(!DateTime.TryParse(string.Format("01 {0} {1}",Month,Year),out date))
                throw new ArgumentException("Instance is not a valid Period!");         
            return date.GetHashCode();
        }
    }

    public override bool Equals(object obj)
    {
        return this.CompareTo(obj)==0;
    }

    public static bool operator==(Period left, Period right)
    {
        return left.Equals(right);
    }

    public static bool operator!=(Period left, Period right)
    {
        return !(left==right);
    }

    public static bool operator<(Period left, Period right)
    {
        return left.CompareTo(right)<0;
    }

    public static bool operator>(Period left, Period right)
    {
        return left.CompareTo(right)>0;
    }

    public override string ToString()
    {
        if(string.IsNullOrWhiteSpace(Month))
            return string.Empty;
        else if(Month=="Present")
            return Month;
        else 
            return string.Format("{0} {1}",Month,Year);
    }

    public string Month{get; set;}
    public int Year{get; set;}
}

Sample DEMO

in sql i created the following datatype

create type Period from nvarchar(8) not null;

Questions:

  1. How can i define Period in sql?
  2. How can i tell EntityFramework to link period to the data type period in sql?

any idea will be appreciated

3
  • I dont think there is any validation for this in ef.You can do it by using custom validation for both client and server.Do you require any client validation also? Else you can just add couple of code in server or extend a new filter for it.
    – Binod
    Jan 1, 2015 at 8:36
  • i think there is a way i am sure since EF is a great technology and sure they didn't miss this details, i am waiting to see if anyone can confirm this or i will be disappointed
    – Monah
    Jan 1, 2015 at 9:19
  • try to use compare attribute inherit from ValidationAttribute.
    – Binod
    Jan 1, 2015 at 10:24

1 Answer 1

0
+50

here a workaround about how to do it

your experience class will be like this

public class Experience
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Company { get; set; }
    public Period FromDate { get; set; }
    public Period ToDate { get; set; }
    public string Description { get; set; }
}

change the following in your period class which will be a [ComplexType]

// change the folllowing
[NotMapped]
public string Month{get; set;}
[NotMapped]
public int Year{get; set;}

// add this property to use it for EntityFramework mapping
public string Date
{
    get
    {
        return ToString();
    }
    set
    {
        if (!string.IsNullOrEmpty(Date))
            {
                if (Date == "Present")
                    Month = "Present";
                else
                {
                    var split = Date.Split(' ');
                    Month = split[0];
                    Year = Convert.ToInt32(split[1]);
                }
            }
        }
    }

in your Mapping you do the following

 modelBuilder.Entity<Experience>()
                .Property(t => t.FromDate.Date)
                .IsRequired()
                .HasMaxLength(8);

 modelBuilder.Entity<Experience>()
            .Property(t => t.ToDate.Date)
            .IsRequired()
            .HasMaxLength(8);

to let the entity framework to make the fields as Period datatype, you can do this 1- enable-migration 2- add-migration first // this will create a file dbmigration that has the database and table construction 3- in the function Up at end you write the following using Sql(@"");, here i will put the sql statements for you

create function CheckPeriod(@period nvarchar(8)) -- this function will make sure that Period is valid
returns bit
as
begin
    declare @month nvarchar(3)
    if ( @period is null )
        return 0
    if( @period = 'Present')
        return 1;
    set @month=substring(@period,0,3)
    if(@month in ('Jan','Feb','Mar','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'))
        return 1;
    return isdate(@period);
end

create function CheckValidity(@right as nvarchar(8),@left as nvarchar(8)) -- this function will compare FromDate to ToDate and return valid if ToDate>FromDate
returns bit
as
begin
    if(@right='Present')
        return 0;
    if(@left='Present' and cast(@right as date)>=getdate())
        return 0;
    if(@left='Present')
        return 1;
    if(cast(@left as date)>cast(@right as date))
        return 1;
    return 0;
end

exec sp_addtype 'Period','nvarchar(8)','NOT NULL'


alter table Experiences alter column FromDate Period
alter table Experiences alter column ToDate Period

alter table Experiences
add constraint FromDateIsPeriod check ( dbo.CheckPeriod(FromDate)=1)

alter table Experiences
add constraint ToDateIsPeriod check ( dbo.CheckPeriod(ToDate)=1)

alter table Experiences
add constraint PeriodValidity check ( dbo.CheckValidity(FromDate,ToDate)=1)

and in the Down function if you want you write the code to drop the functions and to alter the table fields to return them back as nvarchar(8) and finally to drop the datatype Period

hope this will help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.