1

I am creating a very simple EF4 code first project with one entity.

public class Activity
{
    public Guid Id { get; set; }
    public string Description { get; set; }
    public List<DateTime> DateDone { get; set; }
    <snip>

    public Activity()
    {
        if(DateDone==null)
            DateDone = new List<DateTime>();
    }
}

I rebuild my project and then run the MVC3 app and the database generates (confirmed, I have added and removed columns), my data is seeded (it changes on screen when I modify the seeded data)

I am able to:

var activity = db.Activities.Find(id);
activity.DateDone = DateTime.Now;
db.SaveChanges();

But the data isn't saved. I have checked the database as there is only the one table (Activity) and it has all the appropriate fields. I expect it should have a second table though, ActivityDateDone with two fields, ActivityGuid & DateDone.

What am I missing on making this work?

Nathan Koop
  • 24,803
  • 25
  • 90
  • 125

3 Answers3

7

Entity Framework does not support collections of primitive types.

You need to define a separate class to hold the DateTimes.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

DateTime is not an entity. You need to create a model class if you want code first to create data structures for you. I assume your activity table has a DateDone Column?

Maess
  • 4,118
  • 20
  • 29
0

While Entity Framework does not support this natively, you can make it work quite nicely.

Please see this answer for the additional code(PersistableScalarCollection) and original idea: https://stackoverflow.com/a/11990836/1742393

/// <summary>
///     ALlows persisting of a simple DateTime collection.
/// </summary>
[ComplexType]
public class PersistableDateTimeCollection : PersistableScalarCollection<DateTime>
{
    protected override DateTime ConvertSingleValueToRuntime(string rawValue)
    {
        return DateTime.Parse(rawValue);
    }

    protected override string ConvertSingleValueToPersistable(DateTime value)
    {
        return value.ToShortDateString();
    }
}
Community
  • 1
  • 1
rbj325
  • 954
  • 8
  • 17