我刚完成本教程:http://www.asp.net/web-api/tutorials/hands-on-labs/build-restful-apis-with-aspnet-web-api。我想开始使用本地数据库来存储联系人而不是浏览器缓存。我在App_data中创建了一个SQL Server Compact 4.本地数据库,并创建了一个Contacts模式表。
现在我不确定将项目插入数据库的方法是什么。我需要使用实体框架吗?我是否需要为DB创建新的控制器?
现在处理存储的代码:
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。
答案 0 :(得分:0)
您可能需要查看以下教程:http://www.asp.net/mvc/tutorials/mvc-5/database-first-development/setting-up-database。您可以浏览本教程,因为您已经设置了数据库,在底部只需单击下一步,然后在下一页开始“生成模型”,因为您还创建了现有解决方案。
这些教程使用EF和VS2013。有什么好处是它会使用你的本地数据库为你自动创建Insert / Update / Delete语句(教程的第3步:'生成视图')。
希望有所帮助。