【问题标题】:Migrating from persistent cache storage to Entity Framework with local database从持久缓存存储迁移到具有本地数据库的实体框架
【发布时间】:2014-02-12 19:49:24
【问题描述】:

我刚刚完成了本教程:http://www.asp.net/web-api/tutorials/hands-on-labs/build-restful-apis-with-aspnet-web-api。我想开始使用本地数据库来存储联系人,而不是在浏览器缓存中。我在 App_data 中创建了一个 SQL Server Compact 4.本地数据库并创建了一个联系人架构表。

现在我不确定将项目插入数据库的方法是什么。我需要使用实体框架吗?我需要为数据库创建一个新的控制器吗?

现在处理存储的代码:

public class ContactRepository
{
    private const string CacheKey = "ContactStore";

    //constructor
    public ContactRepository()
    {
        //grab context domain
        var ctx = HttpContext.Current;

        if (ctx != null)
        {
            if (ctx.Cache[CacheKey] == null)
            {
                var contacts = new Contact[]
                {
                    new Contact
                    {
                        Id = 1, Name = "Glenn Block"
                    },
                    new Contact
                    {
                        Id = 2, Name = "Dan Roth"
                    }
                };
                //add contacts array as value to Cache[CacheKey] key
                ctx.Cache[CacheKey] = contacts;
            }
        }
    }
    public Contact[] GetAllContacts()
    {
        var ctx = HttpContext.Current;

        if (ctx != null)
        {
            //return as array of Contact objects
            return (Contact[])ctx.Cache[CacheKey];
        }

        //there are no contacts stored
        return new Contact[]
        {
            new Contact
            {
                Id = 0,
                Name = "Placeholder"
            }
        };
    }

    public bool SaveContact(Contact contact)
    {
        var ctx = HttpContext.Current;

        if (ctx != null)
        {
            try
            {
                //grab contact array, convert to List, add, convert back to Array
                var currentData = ((Contact[])ctx.Cache[CacheKey]).ToList();
                currentData.Add(contact);
                ctx.Cache[CacheKey] = currentData.ToArray();

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return false;
            }
        }

        return false;
    }
}

我想替换上面的代码以使用 localDB。

【问题讨论】:

    标签: c# asp.net entity-framework asp.net-web-api database-migration


    【解决方案1】:

    您可能想查看以下教程:http://www.asp.net/mvc/tutorials/mvc-5/database-first-development/setting-up-database。您可以浏览本教程,因为您已经设置了数据库并在底部单击下一步,然后在下一页上从“生成模型”开始,因为您还创建了现有解决方案。

    这些教程使用 EF 和 VS2013。这样做的好处是它会使用本地数据库自动为您创建插入/更新/删除语句(本教程的第 3 步:“生成视图”)。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-09
      • 2014-11-22
      • 2015-04-24
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-08
      相关资源
      最近更新 更多