Execute array into DB by Dapper - sql

If string Subject = "Hello"; and int[] Category = new int[] { 1, 3, 5, 7, 9 };
How can i insert above variables into DB with one execute session? (i'm using Dapper)
My sql stored procedure:
CREATE PROCEDURE [dbo].[TKNewTicket]
#Subject nvarchar(max),
#Category int
AS
BEGIN
SET NOCOUNT ON;
DECLARE #ObjectID [int]
INSERT INTO dbo.TKTickets(Subject) VALUES (#Subject)
SET #ObjectID = SCOPE_IDENTITY()
INSERT INTO dbo.TKTicketCategory(TicketId, CategoryId) VALUES(#ObjectID, #Category)
END
GO
My Tables:
CREATE TABLE [dbo].[TKTickets] (
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[Subject] nvarchar(100) NOT NULL, )
CREATE TABLE [dbo].[TKTicketCategory] (
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[TicketId] INT NULL,
[CategoryId] INT NULL,
CONSTRAINT [FK_TKTicketCategory_TKTickets] FOREIGN KEY ([TicketId]) REFERENCES [TKTickets]([Id]),
CONSTRAINT [FK_TKTicketCategory_TKCategories] FOREIGN KEY ([CategoryId]) REFERENCES [TKCategories]([Id]), )

I figured out.
public static void NewTicket(string Subject, int[] Categories)
{
using (IDbConnection cnn = new SqlConnection(SqlDataAccess.GetConnectionString()))
{
string sql = #"dbo.InsertNewTicket #Subject";
var ObjectId = cnn.Query<int>(sql, new { Subject = Subject }).Single();
foreach(int Category in Categories)
{
sql = #"InsertNewTicketCategory #TicketId, #CategoryId";
cnn.Query(sql, new { TicketId = ObjectId, CategoryId = Category });
}
}
}

Related

Micronaut Data JDBC: How to map a one-to-many relation using enums?

I would like to map a unidirectional one-to-many relation, using Micronaut Data annotations. Considering the object and database models described below, how to map that using Micronaut annotations?
Object model:
import io.micronaut.serde.annotation.Serdeable
#Serdeable
enum class Role {
Admin, Manager
}
import io.micronaut.data.annotation.GeneratedValue
import io.micronaut.data.annotation.Id
import io.micronaut.data.annotation.MappedEntity
import io.micronaut.serde.annotation.Serdeable
#Serdeable
#MappedEntity
data class User(
#field:Id
#field:GeneratedValue
var id: Long? = null,
val username: String,
// How to map?
var roles: Set<Role>?
)
Database model with many-to-many (DDLs for PostgreSQL):
CREATE TABLE "user"
(
id SERIAL PRIMARY KEY,
username VARCHAR(30) NOT NULL UNIQUE
);
CREATE TABLE "role"
(
id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL
);
CREATE TABLE "user_role"
(
user_id INTEGER REFERENCES "user" (id),
role_id INTEGER REFERENCES "role" (id)
);
INSERT INTO "role" (id, name) VALUES (1, 'Admin'), (2, 'Manager');
Or another option, a simpler database model using one-to-many (PostgeSQL):
CREATE TABLE "user"
(
id SERIAL PRIMARY KEY,
username VARCHAR(30) NOT NULL UNIQUE
);
CREATE TYPE role_name AS ENUM ('Admin', 'Manager');
CREATE TABLE "user_role"
(
user_id INTEGER NOT NULL REFERENCES "user" (id),
role_id INTEGER NOT NULL REFERENCES "role" (id),
CONSTRAINT user_role_uk UNIQUE (user_id, role_id)
);
You may suggest modifications to any database model to allow the one-to-many relation in the object model.
Here are two out of the multiple ways that it could be done. I combined them into one example out of laziness.
#Serdeable
enum class Role {
Admin, Manager;
}
#Serdeable
#MappedEntity
data class UserRole(
#field:Id
#GeneratedValue
var id: Long? = null,
#Nullable
#Relation(value = Relation.Kind.MANY_TO_ONE)
val user: User?,
val role: Role
)
#Serdeable
#MappedEntity
class User(
#field:Id
#field:GeneratedValue
var id: Long? = null,
val username: String,
#MappedProperty(definition = "VARCHAR(30)[]", type = DataType.STRING_ARRAY)
var roles: Set<Role>?,
#Relation(value = Relation.Kind.ONE_TO_MANY, mappedBy = "user", cascade = [Cascade.ALL])
var userRoles: Set<UserRole>?
)
#JdbcRepository(dialect = Dialect.POSTGRES)
#Join(value = "userRoles", type = Join.Type.LEFT_FETCH)
interface UserRepository : CrudRepository<User, Long> {
}
CREATE TYPE role_name AS ENUM ('Admin', 'Manager');
CREATE TABLE "user"
(
id SERIAL PRIMARY KEY,
username VARCHAR(30) NOT NULL UNIQUE,
roles VARCHAR(15)[]
);
CREATE TABLE "user_role"
(
id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
user_id INTEGER REFERENCES "user" (id),
role role_name NOT NULL,
CONSTRAINT user_role_uk UNIQUE (user_id, role)
);

SQL subquery filters data but conversion to JPA with subquery does not filter

Tree, Treetag and Tag tables with example data
A tree belongs to a given farm and each farm has its own set of tags.
Each tree can have zero or multiple tags attached to it.
Same tag can be attached to multiple trees.
DDL -
DROP TABLE tree_tag;
DROP TABLE tag;
DROP TABLE tree;
DROP TABLE farm;
CREATE TABLE farm (
id VARCHAR2(36 CHAR) NOT NULL,
description VARCHAR2(255 CHAR) NULL,
name VARCHAR2(255 CHAR) NOT NULL,
PRIMARY KEY ( id )
);
CREATE TABLE tree (
id VARCHAR2(36 CHAR) NOT NULL,
name VARCHAR2(255 CHAR) NOT NULL,
description VARCHAR2(255 CHAR) NULL,
farm_id VARCHAR2(36 CHAR) NOT NULL,
PRIMARY KEY ( id )
);
CREATE TABLE tag (
id VARCHAR2(36 CHAR) NOT NULL,
farm_id VARCHAR2(36 CHAR) NOT NULL,
name VARCHAR2(255 CHAR) NOT NULL,
description VARCHAR2(255 CHAR) NULL,
PRIMARY KEY ( id )
);
CREATE TABLE tree_tag (
id VARCHAR2(36 CHAR) NOT NULL,
tag_id VARCHAR2(36 CHAR) NOT NULL,
tree_id VARCHAR2(36 CHAR) NOT NULL,
value VARCHAR2(255 CHAR) NULL,
properties VARCHAR2(1000 CHAR) NULL,
PRIMARY KEY ( id )
);
ALTER TABLE tag ADD CONSTRAINT unq_tag0 UNIQUE ( farm_id,
name );
ALTER TABLE tree_tag ADD CONSTRAINT unq_tree_tag0 UNIQUE ( tag_id,
tree_id );
ALTER TABLE tree ADD CONSTRAINT unq_tree0 UNIQUE ( farm_id,
name );
ALTER TABLE tag
ADD CONSTRAINT fk_tagfarm_id FOREIGN KEY ( farm_id )
REFERENCES farm ( id )
ON DELETE CASCADE;
ALTER TABLE tree_tag
ADD CONSTRAINT fk_tree_tagtree_id FOREIGN KEY ( tree_id )
REFERENCES tree ( id )
ON DELETE CASCADE;
ALTER TABLE tree_tag
ADD CONSTRAINT fk_tree_tagtag_id FOREIGN KEY ( tag_id )
REFERENCES tag ( id )
ON DELETE CASCADE;
INSERT INTO farm (
id,
name
) VALUES (
'farm1',
'farm 1 is big'
);
INSERT INTO farm (
id,
name
) VALUES (
'farm2',
'farm 2 is small'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag11',
'farm1',
'juicy'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag12',
'farm1',
'sour'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag13',
'farm1',
'sweet'
);
INSERT INTO tag (
id,
farm_id,
name
) VALUES (
'tag21',
'farm2',
'sour'
);
INSERT INTO tree (
id,
farm_id,
name,
description
) VALUES (
'tree11',
'farm1',
'apple',
'used for jam'
);
INSERT INTO tree (
id,
farm_id,
name
) VALUES (
'tree12',
'farm1',
'cherry'
);
INSERT INTO tree (
id,
farm_id,
name
) VALUES (
'tree13',
'farm1',
'plum'
);
INSERT INTO tree (
id,
farm_id,
name
) VALUES (
'tree21',
'farm2',
'apple'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'1',
'tree11',
'tag12'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'2',
'tree12',
'tag11'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'3',
'tree12',
'tag13'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'4',
'tree13',
'tag12'
);
INSERT INTO tree_tag (
id,
tree_id,
tag_id
) VALUES (
'5',
'tree13',
'tag11'
);
Query:
Want to get a list of trees w/o duplicates where either the name
or the description or the tag name matches the filter in a given
farm
Want to get the count of this unique list of trees in a
given farm
This is a paging request so step 1 query will be called multiple times but step 2 query will be executed only once.
SQL -
This works but when I convert to JPA then subquery is returning all the entries in tree_tag i.e filtering is not happening in JPA subquery
SELECT
t.farm_id,
t.id,
t.name,
t.description
FROM
tree t
WHERE
t.farm_id = :farmid
AND ( lower(t.name) LIKE '%'
|| lower(:filter)
|| '%'
OR lower(t.description) LIKE '%'
|| lower(:filter)
|| '%'
OR ( t.id IN (
SELECT DISTINCT
tt.tree_id
FROM
tree_tag tt, tag ttag
WHERE
tt.tag_id = ttag.id
AND lower(ttag.name) LIKE '%'
|| lower(:filter)
|| '%'
) ) );
SELECT
COUNT(*)
FROM
tree t
WHERE
t.farm_id = :farmid
AND ( lower(t.name) LIKE '%'
|| lower(:filter)
|| '%'
OR lower(t.description) LIKE '%'
|| lower(:filter)
|| '%'
OR ( t.id IN (
SELECT DISTINCT
tt.tree_id
FROM
tree_tag tt, tag ttag
WHERE
tt.tag_id = ttag.id
AND lower(ttag.name) LIKE '%'
|| lower(:filter)
|| '%'
) ) );
JPA -
void buildQuery(EntityManager em, String farmId, String filter) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tree> cq = cb.createQuery(Tree.class);
Root<Tree> tree = cq.from(Tree.class);
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.equal(tree.get("farm").get("id"), farmId));
Predicate namePredicate = cb.like(tree.get(Tree_.name), "%"+filter+"%");
Predicate descriptionPredicate = cb.like(tree.get(Tree_.description), "%"+filter+"%");
Subquery<String> subQuery = cq.subquery(String.class);
Root<TreeTag> treeTagRoot = subQuery.from(TreeTag.class);
Join<TreeTag, Tag> treeTagTagJoin = treeTagRoot.join(TreeTag_.tag);
List<Predicate> subPredicates = new ArrayList<>();
subPredicates.add(cb.equal(treeTagRoot.get(TreeTag_.tag).get(Tag_.id), treeTagTagJoin.get(Tag_.id)));
subPredicates.add(cb.like(treeTagTagJoin.get(Tag_.name), "%"+filter+"%"));
subQuery.select(treeTagRoot.get(Treetag_.tree).get(Tree_.id)).distinct(true).where(subPredicates.toArray(new Predicate[0]));
Predicate inSubQueryPredicate = tree.get(Tree_.id).in(subQuery);
predicates.add(cb.or(namePredicate, descriptionPredicate, inSubQueryPredicate));
cq = cq.where(predicates.toArray(new Predicate[0]));
cq = cq.orderBy(request.buildOrderBy(cb, tree));
TypedQuery<Tree> query = em.createQuery(cq);
List<Tree> trees = query.getResultList();
// for count - using the same query as above but replacing above 2 lines as
// cq = cq.select(cb.count(tree));
// TypedQuery<Long> query = em.createQuery(cq);
// int count = query.getSingleResult().intValue();
}
Entity Classes -
#Entity
#Table(name = "FARM"))
public class Farm {
#Id
#Column(name = "ID")
String id;
public static final String NAME = "name";
public static final String DESCRIPTION = "description";
}
#Entity
#Table(name = "TAG", uniqueConstraints = #UniqueConstraint(columnNames = {"FARM_ID", "NAME"}))
public class Tag {
#Id
#Column(name = "ID")
String id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "FARM_ID", nullable = false, updatable = false)
Farm farm;
#Column(name = "NAME")
protected String name;
#Column(name = "DESCRIPTION")
private String description;
#OneToMany(mappedBy = "tag", fetch = FetchType.LAZY)
#CascadeOnDelete
private List<TreeTag> treeTagList = new ArrayList<>();
}
#MappedSuperclass
public abstract class ResourceTag {
#Id
#Column(name = "ID")
String id;
#ManyToOne
#JoinColumn(name = "TAG_ID", nullable = false)
protected Tag tag;
#Column(name = "VALUE")
protected String value;
}
#Entity
#Table(name = "TREE_TAG", uniqueConstraints = #UniqueConstraint(columnNames = {"TAG_ID", "TREE_ID"}))
public class TreeTag extends ResourceTag {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "TREE_ID", nullable = false)
private Tree tree;
}
#Entity
#Table(name="TREE",uniqueConstraints = #UniqueConstraint(columnNames = {"NAME”,"FARM_ID"}))
public class Tree {
#Id
#Column(name = "ID")
String id;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "FARM_ID", nullable = false)
Farm farm;
#Column(name= "NAME", nullable=false)
private String name;
#Column(name = "DESCRIPTION")
private String description;
#OneToMany(mappedBy = "tree", fetch = FetchType.LAZY)
#CascadeOnDelete
#BatchFetch(value=BatchFetchType.JOIN)
private List<TreeTag> treeTagList = new ArrayList<>();
}
How can I make this JPA code work for both the list and count? Thanks

JPA - I get multiple rows instead of 1

I spent many hours to solve my problem but without success. I'd like to achieve something like this (but with ONE row instead of TWO):
My database:
CREATE TABLE odo.d_kryterium_naruszen (
id bigserial primary key,
kryterium text not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
CREATE TABLE odo.d_czynnik_naruszen (
id bigserial primary key,
czynnik text not null,
id_kryterium_naruszen bigint not null references odo.d_kryterium_naruszen(id),
stopien NUMERIC(10,2) not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
CREATE TABLE odo.d_dotkliwosc_naruszenia (
id bigserial primary key,
zakres numrange not null,
ocena text not null,
opis text not null,
wymagane_dzialanie text not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
CREATE TABLE odo.ocena_naruszenia_wynik (
id bigserial primary key,
wartosc_dotkliwosci_naruszenia NUMERIC(10,2) not null,
status_id bigint not null references odo.d_status_oceny_naruszenia(id),
ocena_naruszenia_id bigint not null references odo.ocena_naruszenia(id),
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
create table odo.czynnik_naruszen_wynik(
id bigserial primary key,
ocena_naruszenia_wynik_id bigint not null references odo.ocena_naruszenia_wynik(id),
czynnik_naruszen_id bigint not null references odo.d_czynnik_naruszen(id),
komentarz text,
czynnik_wybrany boolean not null default false
wartosc_wybrana NUMERIC(10,2) not null,
data_wpr TIMESTAMP not null DEFAULT clock_timestamp(),
opr bigint not null
);
And here my entities:
#Data
#Entity
#Table(schema = "odo", name = "d_kryterium_naruszen")
public class ViolationCriterion extends BaseEntity {
#Column(name = "kryterium")
private String criterion;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
#JoinColumn(name = "id_kryterium_naruszen")
private List<ViolationFactor> violationFactors;
}
#Data
#Entity
#Table(schema = "odo", name = "d_czynnik_naruszen")
public class ViolationFactor extends BaseEntity {
#Column(name = "czynnik")
private String factor;
#Column(name = "stopien")
private float degree;
#OneToMany
#JoinColumn(name = "czynnik_naruszen_id")
private List<IncidentAssessmentFactor> incidentAssessmentFactor;
}
#Data
#Entity
#Table(schema = "odo", name = "czynnik_naruszen_wynik")
public class IncidentAssessmentFactor extends BaseEntity {
#Column(name="komentarz")
private String comment;
#Column(name="czynnik_wybrany")
private Boolean factorIsSelected;
#Column(name = "wartosc_wybrana")
private Float value;
#OneToOne(fetch = FetchType.LAZY)
#JoinColumn(name="ocena_naruszenia_wynik_id", updatable=false, insertable=false)
private IncidentAssessment incidentAssessment;
}
#Data
#Entity
#Table(schema = "odo", name = "ocena_naruszenia_wynik")
public class IncidentAssessment extends BaseEntity {
#Column(name="ocena_naruszenia_id")
private Long incidentAssessmentId;
#Column(name = "wartosc_dotkliwosci_naruszenia")
private Float severityDegreeValue;
My repository:
#Repository
public interface ViolationCriterionRepository extends JpaRepository<ViolationCriterion, Long> {
// #Query("select vc from ViolationCriterion vc inner join vc.violationFactors vf inner join vf.incidentAssessmentFactor iaf inner join iaf.incidentAssessment ia where ia.incidentAssessmentId = ?1 group by vc ")
#Query("select vc from ViolationCriterion vc inner join vc.violationFactors vf inner join vf.incidentAssessmentFactor iaf inner join iaf.incidentAssessment ia where ia.incidentAssessmentId = ?1 group by vc ")
// #Query(value = "select kn.kryterium from odo.d_kryterium_naruszen kn join odo.d_czynnik_naruszen cn on kn.id = cn.id_kryterium_naruszen join odo.czynnik_naruszen_wynik cnw on cnw.czynnik_naruszen_id = cn.id join odo.ocena_naruszenia_wynik onw on cnw.ocena_naruszenia_wynik_id = onw.id where onw.ocena_naruszenia_id = ?1 group by kn.id, cn.id, cnw.id, onw.id", nativeQuery = true)
// #Query(value = "select kn.id, kn.kryterium, kn.data_wpr, kn.opr, cn.id, cn.czynnik, cn.stopien, cn.opr, cn.data_wpr, cnw.id, cnw.data_wpr, cnw.opr, cnw.komentarz, cnw.czynnik_wybrany, cnw.wartosc_wybrana, onw.id, onw.data_wpr, onw.opr, onw.ocena_naruszenia_id, onw.wartosc_dotkliwosci_naruszenia from odo.d_kryterium_naruszen kn join odo.d_czynnik_naruszen cn on kn.id = cn.id_kryterium_naruszen join odo.czynnik_naruszen_wynik cnw on cnw.czynnik_naruszen_id = cn.id join odo.ocena_naruszenia_wynik onw on cnw.ocena_naruszenia_wynik_id = onw.id where onw.ocena_naruszenia_id = ?1 group by kn.id, cn.id, cnw.id, onw.id", nativeQuery = true)
List<ViolationCriterion> findIncidentAssessmentByIncidentAssessmentId(Long incidentId);
// List<ViolationCriterion> findByViolationFactorsIncidentAssessmentFactorIncidentAssessmentIncidentAssessmentIdGroupByViolationCriterionCriterion(Long id);
}
And here I call my repository:
List<ViolationCriterion> violationCriteria = violationCriterionRepository.findIncidentAssessmentByIncidentAssessmentId(id);//vi
In a table czynnik_naruszen_wynik I have 2 different rows because I have 2 rows in table ocena_naruszenia_wynik. The problem is that I have multiple values of entity IncidentAssessmentFactor instead of 1

The data reader is incompatible with the specified Model in MVC4

I am developing my Application in MVC. I am using stored procedure to insert the values in the database. While adding the code in MVC i am getting an error. I will share my code here.
WaitingList Table
[WaitingListId] [int] IDENTITY(1,1) NOT NULL,
Primary Key - [CustomerId] [int] NULL,
Foreign key - [BusinessCategoryId] [int] NULL,
Foreign key - [BusinessId] [int] NULL,
Foreign key - [LocationId] [int] NULL,
Foreign key - [EmployeeId] [int] NULL,
[WaitingOrder] [int] NULL,
[Status] [nvarchar](50) NULL
Stored Procedure
Alter procedure sp_waitinglist
#businessid int,
#customerid int,
#busictgryid int,
#locid int,
#empid int,
#sts nvarchar(50)
As
declare #MaxVal as int
Begin
If EXISTS(select * from tbl_WaitingList where BusinessId = #businessid )
Begin
SET #MaxVal = (SELECT MAX(WaitingOrder) +1 from tbl_WaitingList where BusinessId = #businessid )
insert into tbl_WaitingList(CustomerId, BusinessCategoryId,BusinessId,LocationId, EmployeeId, WaitingOrder, Status) values(#customerid, #busictgryid, #businessid,#locid,#empid,#MaxVal, 'yy')
End
else
Begin
SET #MaxVal= 1
insert into tbl_WaitingList(CustomerId, BusinessCategoryId,BusinessId,LocationId, EmployeeId, WaitingOrder, Status) values(#customerid, #busictgryid, #businessid,#locid,#empid,#MaxVal, 'yy')
End
End
MVC Controller Code
public ActionResult WaitingList()
{
SYTEntities ca = new SYTEntities();
ViewBag.CategoryId = new SelectList(ca.BusinessCategories.ToList(), "CategoryId", "CategoryName");
ViewBag.Service = new SelectList(ca.tblBusinessCategories.ToList(), "BusinessID", "BusinessName");
return View();
}
[HttpPost]
public ActionResult WaitingList(string Business, string Service, string Location, string Employee)
{
ViewBag.CategoryId = new SelectList(db.BusinessCategories.ToList(), "CategoryId", "CategoryName");
ViewBag.Service = new SelectList(db.tblBusinessCategories.ToList(), "BusinessID", "BusinessName");
var param = new SqlParameter[6];
param[0] = new SqlParameter { ParameterName = "#businessid", Value = Service };
param[1] = new SqlParameter { ParameterName = "#customerid", Value = (int)Session["UserID"] };
param[2] = new SqlParameter { ParameterName = "#busictgryid", Value = Business };
param[3] = new SqlParameter { ParameterName = "#locid", Value = Location };
param[4] = new SqlParameter { ParameterName = "#empid", Value = Employee };
param[5] = new SqlParameter { ParameterName = "#sts", Value = "gg" };
List<tbl_WaitingList> waiting = new List<tbl_WaitingList>();
using (SYTEntities context = new SYTEntities())
{
waiting = context.Database.SqlQuery<tbl_WaitingList>("exec sp_waitinglist #businessid,#customerid,#busictgryid,#locid,#empid, #sts", param).ToList();
}
db.SaveChanges();
return View();
}
View Page
#using (Html.BeginForm("WaitingList", "Appt", FormMethod.Post))
{
<div>
#Html.DropDownList("Business", ViewBag.CategoryID as SelectList ,"Select the Business Category", new { id = "Business" })
</div>
<div>
<label>Select the Service Type</label>
#*<select id="Buname" name="buname" style="width:150px"></select>*#
#Html.DropDownList("Service", ViewBag.Service as SelectList,"Select", new { id = "Service", name ="buname"})
</div>
<div>
<label> Select the Location</label>
<select id="Location" name="location" style="width:150px"></select>
</div>
<div>
<label> Select the Location</label>
<select id="Employee" name="employee" style="width:150px"></select>
</div>
<div>
<input type="submit" name="btn" value="Add me into waiting list"/>
</div>
}
Error is
The data reader is incompatible with the specified 'SYTModel.tbl_WaitingList'. A member of the type, 'WaitingListId', does not have a corresponding column in the data reader with the same name.
My Error Page is
I am getting an error like this. Can anyone please help me to solve this.
Thanks in Advance.
You should supply the SqlParameter instances in the following way:
context.Database.SqlQuery<tbl_WaitingList>(
"mySpName #param1, #param2, #param3",
new SqlParameter("param1", param1),
new SqlParameter("param2", param2),
new SqlParameter("param3", param3)
);

SimpleMembership Could not drop constraint

When executing:
ALTER TABLE [dbo].[webpages_UsersInRoles] DROP CONSTRAINT [FK_dbo.webpages_UsersInRoles_dbo.webpages_Membership_UserId]
I receive an error:
'FK_dbo.webpages_UsersInRoles_dbo.webpages_Membership_UserId' is not a constraint.
Could not drop constraint. See previous errors.
This is my webpages_UsersInRoles table:
CREATE TABLE [dbo].[webpages_UsersInRoles] (
[UserId] INT NOT NULL,
[RoleId] INT NOT NULL,
PRIMARY KEY CLUSTERED ([UserId] ASC, [RoleId] ASC),
CONSTRAINT [fk_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[UserProfile] ([UserId]),
CONSTRAINT [fk_RoleId] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[webpages_Roles] ([RoleId])
);
I tried doing following this answer, but it didn't work for me.
you can try this:
[Authorize(Roles = "Admin")]
[HttpPost]
public ActionResult DeleteUser(int id)
{
var tmpuser = "";
var ctx = new UsersContext();
using (ctx)
{
var firstOrDefault = ctx.UserProfiles.FirstOrDefault(us => us.UserId==id);
if (firstOrDefault != null)
tmpuser = firstOrDefault.UserName;
}
string[] allRoles = Roles.GetRolesForUser(tmpuser);
Roles.RemoveUserFromRoles(tmpuser,allRoles);
//Roles.RemoveUserFromRole(tmpuser, "RoleName");
((SimpleMembershipProvider)Membership.Provider).DeleteAccount(tmpuser);
Membership.Provider.DeleteUser(tmpuser, true);
Membership.DeleteUser(tmpuser, true);
ctx = new UsersContext();
return View(ctx.UserProfiles.OrderBy(user => user.UserName).ToList());
}