I want create controller in mvc 4 (vs 2012)
"MVC controller with read/write action and view using Entity Framwork"
But I can't choose my model class.
my model class
public class Authorss
{
public int id { get; set; }
public string name{get;set;}
}
public class ModelContext : DbContext
{
public DbSet Authors { get; set; }
}
I decided this problem. When I create model class, I don't rebuild my project and when I want to choose model class, it was don't visible.
Related
I'm trying to use scaffolding to generate MVC Controller with views, using Entity Framework:
I created ApplicationDBContext:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<med1.Models.House> House { get; set; }
}
and added to ConfigureServices:
services.AddDbContext<Data.ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
And of course I have House model:
public class House
{
public int ID { get; set; }
public string HouseName { get; set; }
public string Address1 { get; set; }
public int CityID { get; set; }
public City City { get; set; }
public string ZIP { get; set; }
public int StateID { get; set; }
public State State { get; set; }
}
I got following error:
Okay, I added parameterless constructor to ApplicationDBContext:
public ApplicationDbContext() { }
And got the following error:.
Actually I had the same problem with previous project and created Controller and View manually.
But for this project I'd like to use scaffolding.
I'm doing something wrong or it's VS 2017 preview problem?
You may be missing this part -
public class AppDbContextFactory : IDbContextFactory<AppDbContext>
{
public AppDbContext Create(string[] args) =>
Program.BuildWebHost(args).Services.GetRequiredService<AppDbContext>();
}
Once you enable scaffolding in your ASP.NET Core 2.0 project and created model name as 'House', follow these steps-
Step1: Right click on the Controllers folder in Solution Explorer and select Add > New Scaffolded Item.
Step2: Select 'MVC Controller with View, using Entity Framework' and click on Add.
Step3: In Add Controller, select House Model and use plus(+) sign to create new AppDbContext. It will also add above mentioned AppDbContextFactory.
After finishing step3, you will have HousesController in Controllers folder and corresponding Houses folder inside views folder.
This is my AppDbContext looks like-
public class AppDbContext : DbContext
{
public AppDbContext (DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<AspNetCore200_VS2017preview1_scaffolding.Models.House> House { get; set; }
}
Hope this helps to proceed further.
Copy contents of the following path of your application
"bin\Debug\netcoreapp1.1"
to
"bin\MCD\Debug\netcoreapp1.1"
This solved the issue for me
I am building a Web API and have two models: Task and Feature:
public class Feature
{
[Key]
public long FeatureId { get; set; }
public string Analyst_comment { get; set; }
public virtual ICollection<User_Task> Tasks { get; set; }
public Feature()
{
}
}
public class User_Task
{
[Key]
public long TaskId { get; set; }
public string What { get; set; }
[ForeignKey("FeatureId")]
public long? FeatureId { get; set; }
public User_Task()
{
}
}
I create Tasks first and then create a Feature that combines few of them. Task creation is successful, however while creating a Feature with existing Tasks, my controller throws an error saying the task already exists:
My FeatureController has following method:
//Create
[HttpPost]
public IActionResult Create([FromBody] Feature item)
{
if (item == null)
{
return BadRequest();
}
** It basically expects that I am creating a Feature with brand new tasks, so I guess I will need some logic here to tell EF Core that incoming tasks with this feature already exist **
_featureRepository.Add(item);
return CreatedAtRoute("GetFeature", new { id = item.FeatureId }, item);
}
How to tell EF core that incoming Feature has Tasks that already exist and it just needs to update the references instead of creating new ones?
My context:
public class WebAPIDataContext : DbContext
{
public WebAPIDataContext(DbContextOptions<WebAPIDataContext> options)
: base(options)
{
}
public DbSet<User_Task> User_Tasks { get; set; }
public DbSet<Feature> Features { get; set; }
}
And repo:
public void Add(Feature item)
{
_context.Features.Add(item);
_context.SaveChanges();
}
When calling Add on a DBSet with a model that was not loaded from EF, it thinks it is untracked and will always assume it is new.
Instead, you need to load the existing record from the dbcontext and map the properties from the data passed into the API to the existing record. Typically that is a manual map from parameter object to domain. Then if you return an object back, you would map that new domain object to a DTO. You can use services like AutoMapper to map the domain to a DTO. When you're done mapping, you only need to call SaveChanges.
Generally speaking, loading the record and mapping the fields is a good thing for the security of your API. You wouldn't want to assume that the passed in data is pristine and honest. When you give the calling code access to all the properties of the entity, you may not be expecting them to change all the fields, and some of those fields could be sensitive.
I am trying to create a SPA model which is able to create, update, delete scheduled tasks in Visual Studio 2012 using MVC4 Hottowel SPA template. Here i have a demo class which I need to use in creating database but unable to get 1) the context of the database.
2) how to configure the database in this project. I tried with creating connection using (LocalDb)\v11.0 sql server but its showing error that entity framework 6 or above is not supported with this application.
public class JobDemo
{
public string JobName { get; set; }
public string JobDescription { get; set; }
public string Frequency { get; set; }
public bool JobStatus { get; set; }
public bool JobIsActive { get; set; }
public DateTime LastModifiedOn { get; set; }
}
This is my class which I wanna use to create database of scheduled tasks/jobs and then query on them
public class DemoDb : DbContext
{
public DbSet<JobDemo> Jobject { get; set; }
public DemoDb() : base("name=DefaultConnection")
{
}
}
The class is creating the DbContext of my JobDemo Class. But after that i am unable to create database connection which use my class and use the following attributes defined in my JobDemo class.
Even though the EF6 is not supported in SPA template, the SqlServer or SqlServerCompact Database can be used with HotTowel SPA template as they support the model and can be used with Breeze Api or Simple controllers with get and post methods can be used to retrieve and store data.
I have two classes with a Many-to-Many relationship. When I save my context, Entity Framework is not using the existing Ids, it creates new entry in my database.
My classes are the following : Country and CountryGroup (in my database EF creates as expected CountryGroupCountries).
public class Country : EntityBase
{
public Country()
{
CountryGroups = new List<CountryGroup>();
}
public virtual List<CountryGroup> CountryGroups { get; set; }
}
public class CountryGroup : EntityBase
{
public CountryGroup()
{
Countries = new List<Country>();
}
public virtual List<Country> Countries { get; set; }
}
public abstract class EntityBase
{
public EntityBase()
{
DateCreate = DateTime.Now;
DateUpdate = DateTime.Now;
DateDelete = DateTime.Now;
}
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
[Required]
public virtual String Name { get; set; }
}
I use ASP MVC 4 and Entity Framework 5. When I want to save a CountryGroup, I use Countries that are already in my website. The Ids are the right one.
public virtual void Save(TEntity entity)
{
EntityRepository.Insert(entity);
Context.SaveChanges();
}
I just want EF to save my object and the relation to the countries but not. What solution do I have here ? I Feel like I have a misunderstanding of the way EF manages Many To Many.
After many research I believe that my problem lies on the model binder. It must be only creating object without getting them from the context. I overridded my Save Method to replace each Countries in the CountryGroup entity with a fresh one from the context. It is not optimal but I'm going to studie the model binding and then I will arbitrate between those solutions.
I am new to MVC but have worked my way through the validation tutorials and they do exactly what I want to do... but.... my model is in a separate portable class library.
How would I add the validation rules to this non-MVC solution so that my MVC website?
Is it possible please?
Thanks
You can create an interface to that class and use impromptu interface to have your class act as that interface...
Lets say this is the class from the portable library:
public class SomeClass
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Create a cloned interface and specify validation attributes in it:
public interface ISomeClass
{
[Required]
string FirstName { get; set; }
string LastName { get; set; }
}
At the top of your view, pass the interface instead of the class:
#model YourNamespace.Models.ISomeClass
In your controller, do:
return View(instanceOfSomeClass.ActLike<ISomeClass>();
You can find impromptu interface here:
http://code.google.com/p/impromptu-interface/
Since the class and the interface look exactly the same, model binding works as well.
Hope this helps.