【发布时间】: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