EF code first List<DateTime> not creating table

核能气质少年 提交于 2019-12-10 11:44:35

问题


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?


回答1:


Entity Framework does not support collections of primitive types.

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




回答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?




回答3:


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();
    }
}


来源:https://stackoverflow.com/questions/8332183/ef-code-first-listdatetime-not-creating-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!