データを調べたり、追加したり、その他のことを行うためのフロントエンドを持つASP.NET MVC Webサイトが必要です。そして、モバイル デバイスなどのデータを取得するための Web Api が必要です。最初に EF からコードを使用したい (そして、Ninject を使用しています)。ホテルなどのクラスを作成しています。HotelManagerContext を作成し、データベースが作成され、見栄えがよくなりました。このために、HomeController と Repository によってデータを追加しています。Visual Studio でデータベースを見ると、そこにデータがあります。しかし、HotelsController for Api を使用しようとすると、datacontext が空になります。どうしたの?何を設定するのを忘れていますか?接続文字列で何か?
これは私の ApiController です:
public class HotelsController : ApiController
{
private IHotelRepository _hotelRepo { get; set; }
public HotelsController(IHotelRepository repo)
{
_hotelRepo = repo;
}
// GET api/Hotels
public IEnumerable<Hotel> GetHotels()
{
return _hotelRepo.GetAll();
}
// GET api/Hotels/5
public Hotel Gethotel(int id)
{
return _hotelRepo.Get(id);
}
}
これは、フロントエンドのコントローラーの一部です。
public class HomeController : Controller
{
private IHotelRepository _hotelRepo { get; set; }
public HomeController(IHotelRepository repo)
{
_hotelRepo = repo;
}
public ActionResult Index()
{
return View();
}
// next methods, for adding data and so
}
これは私のリポジトリです:
public class HotelRepository : IHotelRepository
{
private HotelManagerContext db { get; set; }
public HotelRepository()
:this (new HotelManagerContext())
{
}
public HotelRepository(HotelManagerContext hotelManagerContext)
{
// TODO: Complete member initialization
this.db = hotelManagerContext;
}
public Models.Hotel Get(int id)
{
return db.hotels.SingleOrDefault(h => h.hotId == id);
}
public IQueryable<Models.Hotel> GetAll()
{
return db.hotels;
}
public Hotel Add(Hotel hotel)
{
db.hotels.Add(hotel);
db.SaveChanges();
return hotel;
}
}
これは私の HotelManagerContext です:
public class HotelManagerContext : DbContext
{
public HotelManagerContext() : base("name=HotelManagerContext")
{
}
public DbSet<Hotel> hotels { get; set; }
}
編集:
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IHotelRepository>().To<HotelRepository>();
GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);
}
Edit2:これ が私の接続文字列です:
<add name="HotelManagerContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=HotelManagerContext-20121219191411; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|HotelManagerContext-20121219191411.mdf" providerName="System.Data.SqlClient" />
そして、HomeController でも空のデータコンテキストがあることがわかりました。そのため、サーバー エクスプローラーでデータベースの内容を確認すると、(HomeController に) 追加したデータがあります。しかし、リクエスト ページ (Web API またはフロントエンド) があるたびに、datacontext が空で、ゼロからカウントされている項目を追加できますが、データベースには既に次のものがありますが、取得できません。本当に変です。