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.
Related
I am working on creating an ecommerce website on ASP MVC Core 2. I inherited my user from IdentityUser and inherited context from IdentityDbContext for working with user data and inherited a different context from DbContext for working with products and orders etc.
Now, I want to link an order or shopping cart to a particular user and can not wrap my head around how to refer to the user in order table as they are in different contexts. I am also using the default guid created by EF as primary key in both the tables.
Should I ditch DbContext and use IdentityDbContext only? Does doing this causes problems with async methods in identity and other usual non async methods.
Here are some code snippets from my classes
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace shophe1.Models
{
public enum Gender { Male, Female, Other}
public class User : IdentityUser
{
public string FullName { get; set; }
public Gender Gender { get; set; }
public string ReferralID { get; set; }
public DateTime RegistrationDateTime { get; set; }
public string ActivationDateTime { get; set; }
public string UserType { get; set; }
public Wallet Wallet {get;set;}
public virtual ICollection<UserBankDetail> BankDetails { get; set; }
public virtual ICollection<UserAddress> AddressDetails { get; set; }
//public ShoppingCart Cart { get; set; }
//public ICollection<Order> Orders { get; set; }
}
}
Order class
using System.Collections.Generic;
namespace shophe1.Models
{
public class Order
{
public string OrderId { get; set; }
public ICollection<product> CartProducts { get; set; }
//public User User { get; set; }
public decimal OrderTotal { get; set; }
public decimal ShippingCharges { get; set; }
}
}
The issue is if I add user in order model and a collection of orders in user class, both contexts get mixed up and when migrating, all user and product related models get clubbed in same migration whether I use DbContext or IdentityContext in migrations --context option. This is because both user and orders are now interrelated.
Please advice.
Inherit your context from IdentityDbContext. You should have one context per database, ideally - especially if you want to relate the entities to each other.
If you actually want separate databases, such that the Identity tables reside in one, while your application tables reside in another, then you won't be able to directly relate the entities with each other. However, you can still create a pseudo-foreign key, where you simply store the id of a particular user in a column on one of your entities. You'd then merely need to issue a separate query on the other context with this id to fetch the user manually. For example:
var order = await appContext.Orders.FindAsync(orderId);
var user = await identityContext.Users.FindAsync(order.UserId);
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'm Using Composite keys in below Model class of mvc and same thing.I did in MS SQL Server database having two columns with both are PK,FK but i am getting error in InitializeSimpleMembershipAttribute class like "Exception has been thrown by the target of an invocation" please help me to get how to create.
This is my model class
[Table("webpages_UsersInRoles")]
public partial class UsersInRoles
{
[Column(Order = 0)]
public int RoleId { get; set; }
public virtual NewRoles roles { get; set; }
[Column(Order = 1)]
public int UserId { get; set; }
public virtual UserProfile UserProfiles { get; set; }
}
why you doing that? you dont need to define this yourself. if you use AccountController and if you use WebSecurity Role this table is created for you in SimpleMemberShipInitializer filter. and you just need to use the built in functionality provided for you with SimpleMembership provider.
in short, you dont need to define this table which IMO is the reason you having these problems.
This is my model on the server side. I don't want to use Entity Framework, how would I generate BreezeJS metadata from the server. Breeze Metadata Format found here http://www.breezejs.com/documentation/breeze-metadata-format doesn't work.
public class User
{
public string Id { get; set; }
public string Name { get; set; }
public List<App> Apps { get; set; }
}
public class App
{
public string Id { get; set; }
public string Name { get; set; }
public Dictionary<string, string> Info { get; set; }
}
Did anyone try complex objects (nested object) similar to above one without using EF.
Using Breeze Metdata API or OData ?
Look at this example http://www.breezejs.com/samples/nodb it should give you a clue.
I working to code first technique with EF4.1, WCF webservice, and Sql azure. To improve the performance i wanted to create the View to fetch data at server side. but according to this
we can not use sql View with EF code first.
Because the database and models are defined. it has the data. to re create and dump data for the only creating view is time taking process.
so i just created the View explicitly at sql server.
now I want to call that view from my wfc web service. Now i want to access that view as dataset in WCF. need guidlines. and right approach
Could you define a table in codefirst with the same columns, then create a custom initializer that drops the table from the database and creates it again as a view?
Then you should be able to query it just like normal.
Edit Update to show working example
public class User
{
public int Id { get; set; }
public string Email { get; set; }
}
public class UserView
{
public int Id { get; set; }
public string Email {get; set;}
}
public class TestContext : DbContext
{
static TestContext()
{
Database.SetInitializer<TestContext>(new DatabaseInitializer());
}
public DbSet<User> Users { get; set; }
public DbSet<UserView> UserView { get; set; }
}
class DatabaseInitializer : DropCreateDatabaseIfModelChanges<TestContext>
{
protected override void Seed(TestContext context)
{
base.InitializeDatabase(context);
context.Database.ExecuteSqlCommand("drop table UserViews");
context.Database.ExecuteSqlCommand(#"CREATE VIEW [dbo].[UserViews] AS SELECT *
from [dbo].[Users]
GO");
context.Users.Add(new User() { Email = "test#test.com" });
}
}
...
using (TestContext context = new TestContext())
{
context.UserView.ToList(); //contains all the users
}