3

I have class from model first (EF 4.4 .Net 4.0):

public partial class Test
{
    public int Id {get; set; } 
    public int Date { get; set; }
    //other fields...
}

I can't change database model but I need to override get and set in this class. Something like that:

 [MetadataType(typeof(TestMetadata))]
 public partial class Test
 {
     public class TestMetadata
     {
         private int data;
         public DateTime Date
         {
            get
            {
                return DateTime.Today.Date;
            }
            set
            {
                date = value.Day;
            }
        }
    }

This approach dosen't work. Is it any possibilities to override get set in partial calss?

4
  • Describe what you want to achieve and why would you do that? Give a real-life scenario. Commented Nov 29, 2013 at 10:18
  • I have an old system which date and time keep in int field (in Database). I rewrite old system to C#+EF and I haven't change database structure (because of compatibility). Commented Nov 29, 2013 at 10:26
  • But in you first code property Date is directly in Test class however in next is in TestMetadata. Can you explain what functionality do you want to achieve? Commented Nov 29, 2013 at 10:34
  • First class is from Database (model first) and I can't change them because after update I'll lose chenges. I need get Date from database, convert it into date format and show like (ex. yyy/mm/dd) and next save (set) data into database after coverted into Int (ex. 77768). Commented Nov 29, 2013 at 10:51

2 Answers 2

2

My workaround. Something like that:

public partial class Test
    {
        public DateTime DateSi
        {
            get
            {
                return ConvertIntToDate(Date)
            }
            set
            {
                Date = ConvertDateToInt(value);
            }
        }
    }

In C# I use Test.DateSi (not mapped) and EF save into Database field Date with proper Int value. I only have to remember to use in C# DateSi instead of Date.

Sign up to request clarification or add additional context in comments.

1 Comment

You can even make the Date property private. EF will be able to populate it.
0

Here is a part of solution. I dont understand where (what property) do you want to save converted date. There is no chance to save int to datetime field.

public partial class Test
{
    string format = "yyy/mm/dd";

    public string DateFormat { get { return Date.ToString(format); }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.