I'm trying to make a simple project in ASP.NET, 'code first'.
So I made a class EFDbContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MVCRubenWouters.Models
{
public class EFDbContext: DbContext
{
public EFDbContext() : base("name=rubenwoutersdbCF")
{
Database.SetInitializer<EFDbContext>(new EFDbInitializer());
}
public DbSet<Types> Types { get; set; }
}
}
And added a connectionstring in 'web.config'
<connectionStrings>
<add name="rubenwoutersdbCF" connectionString="Data Source=.\SQLSERVER2012;Initial Catalog=rubenwoutersdbCF;Integrated Security=True;MultipleActiveResultSets=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
Then I created a class "EFDbInitializer to add something to the database:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MVCRubenWouters.Models
{
public class EFDbInitializer: DropCreateDatabaseAlways<EFDbContext>
{
protected override void Seed(EFDbContext context)
{
Types t1 = new Types()
{
PK_TypeNr = 1,
TypeKeuken = "Belgisch",
TypeZaak = "Restaurant",
Vegetarisch = false
};
context.Types.Add(t1);
context.SaveChanges();
}
}
}
When I run the project and go to the SQL server management studio (and refresh), no new database is there..
Am I doing something wrong here? :/
I would suggest you create your database in SQL server, build your tables, then fill them using your code.
The way that runs on my system is force the database in Application_Start()
try this:
Database.SetInitializer(new CreateDatabaseIfNotExists<EFDbContext>());
var context = new EFDbContext("Data Source=(local);Integrated Security=SSPI;Initial Catalog=myDB;");
context.Database.Initialize(true);
I think the seed method is never called, To ensure set a brakpoint
You can develop your custom intializer something like below link:
Seed in entity framework and then call it in Application_Start()
Database.SetInitializer<EFDbContext>(new EFDbInitializer());
Related
I am new to ASP.NET and I am creating a Web API using sort of code first. I have model class call gender and defined as follow
public class Gender
{
public int Id { get; set; }
public string Description { get; set; }
}
I decided to create a new folder call DBContext and inside will defined all my DBContext, so for the gender class I have created GenderDb and look like follow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace BackAPI.Models
{
public class GenderDB : DbContext
{
// not define yet
}
}
However I am having an issue however with DbContext not being defined, apparently I am supposed to use Entity Framework, however I want to create my database not through Visual Studio, but using SQL Server 2014 Express.
I did add my data connection and can see that I created a table in SQL Server, however how do I fix DbContext, if I use EF wouldn't that just create it locally and that not what I want
Entity Framework, along with Migrations, will help you here.
I suggest you check out this tutorial: Code First to a New Database
I am using mvc 5 and ef 6 to build a project. I was simplify the retrieval code by adding some methods to partial class entity context. This is how i do it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;
using System.Linq.Expressions;
using System.Data.Entity.Core;
namespace MyShop.Models
{
public partial class DataEntities
{
public T GetById<T>(object id) where T : class
{
EntityKey key = CreateKey<T>(id);
return (T)GetObjectByKey(key);
}
private EntityKey CreateKey<T>(object id)
{
var type = typeof(T);
return new EntityKey("MyEntities." + "." + type.Name, "Id", id);
}
}
But it error at GetObjectByKey though i was add entityframwork 6.dll in my project, and i tried add some references but it don't work.
Can you help me fix the error.
Thanks you for read.
Phuong
I am attempting to figure out how to host MVC4 apps that were built under different solutions. There are many examples of doing this on SO and on the web using the RazorGenerator nuget package with Areas - it works very well. In my situation, I want to avoid using areas - every application my company develops will be in it's own MVC4 project (then collectively in the same solution).
I've integrated RazorGenerator into my apps, the code gen is working as expected. However, my host solution can not find the View in it's default locations. As an example, I have a Controller/View built in one app called MyAccount/Index.
Controller:
namespace Accounts.Controllers
{
public class MyAccountController : Controller
{
//
// GET: /MyAccount/
public ActionResult Index()
{
return View();
}
}
}
View (as generated from RazorGenerator):
namespace Accounts.Views.MyAccount
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using System.Web.Security;
using System.Web.UI;
using System.Web.WebPages;
[System.CodeDom.Compiler.GeneratedCodeAttribute("RazorGenerator", "1.5.4.0")]
[System.Web.WebPages.PageVirtualPathAttribute("~/Views/MyAccount/Index.cshtml")]
public partial class Index : System.Web.Mvc.WebViewPage<dynamic>
{
public Index()
{
}
public override void Execute()
{
#line 1 "..\..\Views\MyAccount\Index.cshtml"
ViewBag.Title = "Index";
#line default
#line hidden
WriteLiteral("\r\n\r\n<h2>Index</h2>\r\n\r\nMy AccountController Index view.");
}
}
}
I know that by default, the ViewEngines are going to try to find this view in the default locations (Views and Shared), so I added my own ViewEngine to the Engines collection:
MyViewEngine.cs:
public class MyViewEngine : RazorViewEngine
{
private static string[] _viewLocations
= new string[]
{
"~/Accounts/Views/{1}/{0}.cshtml"
};
public MyViewEngine()
{
base.ViewLocationFormats = ViewLocationFormats.Union(_viewLocations).ToArray();
}
}
However, the view still isn't found:
The view 'Index' or its master was not found or no view engine supports the searched locations.
The following locations were searched:
~/Views/MyAccount/Index.cshtml
~/Views/Shared/Index.cshtml
~/Views/MyAccount/Index.aspx
~/Views/MyAccount/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/MyAccount/Index.vbhtml
~/Views/Shared/Index.vbhtml
~/Accounts/Views/MyAccount/Index.cshtml
Maybe I am misunderstanding how the view is located -I had thought it would have been found in Accounts/Views/MyAccount/. Any ideas what I might be doing wrong?
Thanks!
Found my issue - it was due to not having the RazorGeneratorMvcStart warmup code in place. It is generated automatically into the App_Start folder when you add the nuget package, however I erroneously removed it.
I have my controller decorated with: [BasicAuthentication] - however, putting in breakpoints, and stepping through the code, the [BasicAuthentication] never redirects to the Auth.cs (in the Filter folder):
Filter\Auth.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Security;
namespace ebapi.Filter
{
public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
So the override OnActionExecuting never executes - but I cannot see what I've missed. My controller, decorated with [BasicAuthentication] is shown below, but doesn't invoke my Auth.cs shown above:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using ebapi.Filter;
using ebapi.Models;
namespace ebapi.Controllers
{
public class GetBookingsController : ApiController
{
private GetBookingsContext db = new GetBookingsContext();
private ApiMembersContext dba = new ApiMembersContext();
// GET api/GetBookings/5
[BasicAuthentication]
public IEnumerable<GetBooking> GetBooking(long id)
{
Thanks for any help,
Mark
if this helps, I changed the
public class BasicAuthenticationAttribute name to: public class BasicAuthenticationV2Attribute
and changed the decoration to:
[BasicAuthenticationV2]
For whatever reason, this started the authentication again, and it fired with no problem.
I'm assuming there is some sort of caching going on, perhaps from the calling IP to the API - that means it remembers it's already authenticated someone, and doesn't need to again?
If anyone could confirm my thinking, I'd appreciate it.
Thank you,
Mark
Does anyone know any resources regarding to the creation of a custom scheduled task under Telligent 5.5 ?
From what I read, all I need to do is the following:
1.Create a type that implements the ITask2 interface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Telligent.Tasks;
namespace Project.ScheduledTasks
{
public class ReminderTask:ITask2
{
public void Execute()
{
string task = "Please hit the breakpoint here";
}
public void Load(System.Xml.XmlNode node)
{
throw new NotImplementedException();
}
}
}
2.Add the task description in the communityserver.config
<Thread minutes="1">
<task name="ReminderTask" type="Project.ScheduledTasks.ReminderTask, Project.ScheduledTasks" enabled="true" enableShutDown="false"></task>
</Thread>
Do I need to do anything else ?
Please help :).
Yes, that is all that you should need to do. Are you having issues?