EF Core Duplicate entry Exception - asp.net

EF core throws an exception in the project I am working on
MySqlException: Duplicate entry '2' for key 'customers.IX_Customers_UserID'
UserID gives such an error when it is present I do not understand exactly what the error is, please help
public class Context : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Address> Addresses { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//optionsBuilder.UseSqlite("Data Source = Shop.db");
//optionsBuilder.UseSqlServer(#"Data Source = (localdb)\v11.0; Initial Catalog=ShopDb; Integrated Security = SSPI;");
optionsBuilder.UseMySql(#"server=localhost;port=3306;database=ShopDb1;user=root;password=admin123;");
}
public Context()
{
Database.EnsureCreated();
}
}
public class User
{
public int ID { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public Customer Customer { get; set; }
public List<Address> Addresses { get; set; }
}
public class Customer
{
public int ID { get; set; }
public int IdentifyNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public User User { get; set; }
[Required]
public int UserID { get; set; }
}
public class Suplier
{
public int ID { get; set; }
public string Name { get; set; }
public string TaxNumber { get; set; }
}
public class Address
{
public int ID { get; set; }
public string FullName { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public User User { get; set; }
public int UserID { get; set; }
}
public class Product
{
public int ProductID { get; set; }
[MaxLength(100)]
[Required]
public string Name { get; set; }
public decimal Price { get; set; }
public int CategoryID { get; set; }
}
public class Category
{
public int CategoryID { get; set; }
[MaxLength(100)]
[Required]
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (var db = new Context())
{
var customer = new Customer()
{
IdentifyNumber = 123,
FirstName = "Remzi",
LastName = "Balakishiyev",
UserID = 2
};
db.Customers.Add(customer);
db.SaveChanges();
}
Console.ReadLine();
}
static void InsertUsers()
{
var users = new List<User> {
new User() { UserName ="Remzi",Email = "remzi.balakisiyev#gmail.com"},
new User() { UserName ="Xezri",Email = "xezri.balakisiyev#gmail.com"},
new User() { UserName ="Nurane",Email = "nurane.tarverdiyeva#gmail.com"}
};
using (var db = new Context())
{
db.Users.AddRange(users);
db.SaveChanges();
}
}
static void InsertAddresses()
{
var addresses = new List<Address> {
new Address(){FullName = "Remzi Balakisiyev", Title = "Ev addressi", Body = "Masalli",UserID=1},
new Address(){FullName = "Remzi Balakisiyev", Title = "Ish addressi", Body = "Baki",UserID=1},
new Address(){FullName = "Xezri Balakisiyev", Title = "Ev addressi", Body = "Masalli",UserID=2},
new Address(){FullName = "Nurane Tarverdiyeva", Title = "Ev addressi", Body = "Naxcivvan",UserID=3},
new Address(){FullName = "Rena Heyderova", Title = "Ev addressi", Body = "Xachmaz",UserID=2},
new Address(){FullName = "Memmed Bedelov", Title = "Ev addressi", Body = "Sumqayit",UserID=1}
};
using (var db = new Context())
{
db.Addresses.AddRange(addresses);
db.SaveChanges();
Console.WriteLine("Ishledi");
}
}

For each customer entity framework adds a new user with the primary key 2. To add a relationship to the user with id 2 you need to insert a user object to the user property.
var customer = new Customer()
{
IdentifyNumber = 123,
FirstName = "Remzi",
LastName = "Balakishiyev",
User = db.Users.FirstOrDefault(x => x.ID == 2)
};
db.Customers.Add(customer);
db.SaveChanges();

Related

Why is my database table not loading using in ASP.NET Core

I am using a dbinitializer to try and seed data to a couple tables on my database. Everything seems to be ok except my Enrolls table doesn't want to populate. The Enrolls table holds all the List<> values of my Students and Courses. From that Enroll table I should be able to see which student is enrolled in which course. I am following a Microsoft docs tutorial but seem to hit a snag.
The thing is when I include the Enrolls property while creating an object in the initializer the entire database does not seed. However when I comment it out all tables except Enroll seed. I poked around a bit before I came here. Just hoping for a little guidance with some fresh pair of eyes as to where I should check/debug.
Truly hope I asked in a way that is understandable.
This is the DbInitializer:
public static class DbInitializer
{
public static void Initialize(StudentRegistrationContext context)
{
context.Database.EnsureCreated();
// Look for any students.
if (context.Students.Any() )
{
return; // DB has been seeded
}
var students = new Student[]
{
new Student
{
FirstName="A",
LastName="B",
Address = new Address
{
HouseNumber = "19",
Street="A ",
City="C",
Country = "T",
Email="s",
PhoneNumber = "6"
},
**// Enrollments = new List<Enroll> { new Enroll { CourseID = 2, ID=1 } }**
},
},
};
foreach (Student s in students)
{
context.Students.Add(s);
}
context.SaveChanges();
var course = new Course[]
{
new Course{CourseName = "Introduction to Computer Hardware",CourseCode = "ITEC120", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{ CourseName = "Introduction to Operating Systems", CourseCode= "ITEC122", NoOfCredits = 3, Category = Category.COMPULSORY },
new Course{ CourseName = "Programming 1",CourseCode = "ITEC133", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{CourseName = "Human and Computer Interface Design", CourseCode = "ITEC229", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{CourseName = "Webpage Design", CourseCode = "ITEC240", NoOfCredits = 3, Category = Category.COMPULSORY},
new Course{CourseName = "Computer Networks Architecture and Protocol",
};
foreach (Course c in course)
{
context.Course.Add(c);
}
context.SaveChanges();
var teacher = new Advisor[]
{
new Advisor{
FirstName="Teacher",
LastName="One",
Address = new Address{ HouseNumber = "123456",
Street="Teacher Street",
City="College City",
Country = "Trinidad",
Email="teacher#gmail.com",
PhoneNumber = "5648965"
},
Department="Department1",
Specialization=Category.ISD
},
};
foreach (Advisor t in teacher)
{
context.Advisor.Add(t);
}
context.SaveChanges();
var enroll = new Enroll[]
{
new Enroll{CourseID = 2, ID =2 },
};
foreach (Enroll e in enroll)
{
context.Enroll.Add(e);
}
context.SaveChanges();
}
}
My model classes:
public class Enroll
{
public int ID { get; set; }
public int CourseID { get; set; }
public Student Student { get; set; }
public Course Course { get; set; }
// public DateTime RegistrationDate { get; set; }
}
public class Student : Person
{
// public List<Course> Attends { get; set; }
public DateTime RegistrationDate { get; set; }
public List<Enroll> Enrollments { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public string CourseCode { get; set; }
public double NoOfCredits { get; set; }
public Category Category { get; set; }
public List<Enroll> Enrollments { get; set; }
}
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
}
So I figured out my issues. It was a mixture of ...
Editing the OnModelCreating function in the context
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Enroll>()
.HasOne(s => s.Student)
.WithMany(en => en.Enrollments)
.HasForeignKey(fk => fk.ID);
modelBuilder.Entity<Enroll>()
.HasOne(s => s.Course)
.WithMany(en => en.Enrollments)
.HasForeignKey(fk => fk.CourseID);
}
....and making my collection properties virtual:
public class Student : Person
{
public DateTime RegistrationDate { get; set; }
public virtual List<Enroll> Enrollments { get; set; }
}
public class Enroll
{
public int ID { get; set; }
public int CourseID { get; set; }
public virtual Student Student { get; set; }
public virtual Course Course { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public string CourseCode { get; set; }
public double NoOfCredits { get; set; }
public Category Category { get; set; }
public virtual List<Enroll> Enrollments { get; set; }
}
Thanks guys

How to modify database having foreign key in asp.net?

I have two tables: SurveyOption and SurveyQuestion, in my DbModel.
public class SurveyOptions
{
[Key]
public Guid SurveyOptionId { get; set; }
public Guid? SurveyQuestionId { get; set; }
public int? Sequence { get; set; }
[MaxLength(50)]
public string OptionValue { get; set; }
[MaxLength(500)]
public string Description { get; set; }
public Guid? ImageId { get; set; }
}
public class SurveyQuestions
{
[Key]
public Guid SurveyQuestionsId { get; set; }
public Guid? SurveyMasterId { get; set; }
public int? Sequence { get; set; }
[MaxLength(1)]
public string QuestionType { get; set; }
[MaxLength(500)]
public string QuestionText { get; set; }
public bool? Required { get; set; }
public string ExplanationLink { get; set; }
}
SurveyQuestionId is the foreign key in SurveyOption. While making an update query I repeatedly get an error The INSERT statement conflicted with the FOREIGN KEY constraint "FK_SurveyOptions_SurveyQuestions". The conflict occurred in database "MCNITemp", table "dbo.SurveyQuestions", column 'SurveyQuestionsId'.
My ViewModel of SurveyQuestion consist of OptionList. In which each SurveyQuestion holds its own optionList of type List<SurveyOption> and questionList is of type List<SurveyQuestion>
My modify code is the following:
foreach (var question in questionList)
{
var options = question.OptionsList;
foreach (var option in options)
{
var optionData = _mcniDbContext.SurveyOptions.Where(e => e.SurveyOptionId == option.SurveyOptionId).FirstOrDefault();
if (optionData == null)
{
_mcniDbContext.SurveyOptions.Add(new SurveyOptions()
{
OptionValue = option.OptionValue,
Description = option.Description,
Sequence = option.Sequence,
SurveyOptionId = option.SurveyOptionId,
SurveyQuestionId = option.SurveyQuestionId
});
}
else
{
optionData.SurveyOptionId = option.SurveyOptionId;
optionData.SurveyQuestionId = option.SurveyQuestionId;
optionData.Sequence = option.Sequence;
optionData.OptionValue = option.OptionValue;
optionData.Description = option.Description;
_mcniDbContext.Entry(optionData).State = EntityState.Modified;
}
_mcniDbContext.SaveChanges();
}
var questionData = _mcniDbContext.SurveyQuestions.Where(e => e.SurveyQuestionsId == question.SurveyQuestionsId).FirstOrDefault();
questionData.SurveyQuestionsId = question.SurveyQuestionsId;
questionData.SurveyMasterId = surveyMasterId;
questionData.QuestionText = question.QuestionText;
questionData.QuestionType = question.QuestionType;
questionData.Required = question.Required;
_mcniDbContext.Entry(questionData).State = EntityState.Modified;
_mcniDbContext.SaveChanges();
}
In your model you have let EF know how relationships are working. Assuming you have not used Fluent Api for desribing same, your code can be like below (code has not been test):
public class SurveyOptions
{
[Key]
public Guid SurveyOptionId { get; set; }
[ForeignKey("SurveyQuestionId")]
public SurveyQuestion SurveyQuestion {get;set;}
public Guid? SurveyQuestionId { get; set; }
public int? Sequence { get; set; }
[MaxLength(50)]
public string OptionValue { get; set; }
[MaxLength(500)]
public string Description { get; set; }
public Guid? ImageId { get; set; }
}

How to save data in many to many relation without duplicate in my Card table [Entity Framework]

I have a problem. I cannot save cards without duplicates.
I have 3 tables a Deck, Card table and a CardDeck table which is the junction table.
The goal is to store a deck in the database without the cards being duplicated.
Table Card
namespace MTG_Deck.Models
{
public class Card
{
[Key]
public int CardId { get; set; }
public string Name { get; set; }
public string Text { get; set; }
public string Type { get; set; }
public string SetName { get; set; }
public string Artist { get; set; }
public string ManaCost { get; set; }
public string Rarity { get; set; }
public string ImageUrl { get; set; }
public string Toughness { get; set; }
public string Power { get; set; }
public string id { get; set; }
public virtual ICollection<DeckCard> Decks { get; set; }
}
}
Table Deck
namespace MTG_Deck.Models
{
public class Deck
{
[Key]
public int DeckId { get; set; }
[Required]
public string Name { get; set; }
[DataType(DataType.Date)]
public DateTime CreateAt { get; set; }
public User User { get; set; }
public virtual ICollection<DeckCard> Cards { get; set; }
}
}
Table CardDeck
namespace MTG_Deck.Models
{
public class DeckCard
{
public int DeckID { get; set; }
public int CardID { get; set; }
public Deck Deck { get; set; }
public Card Card { get; set; }
}
}
CardDeckRequest contains the content of the request.
namespace MTG_Deck.Models
{
public class CardDeckRequest
{
[Required]
public int UserID { get; set; }
[Required]
public string Token { get; set; }
[Required]
public Deck Deck { get; set; }
[Required]
[MinLength(5, ErrorMessage = "The deck must contain 60 cards.")]
public List<Card> Cards { get; set; }
}
}
Controller
[HttpPost]
public IActionResult Add([FromBody] CardDeckRequest request)
{
User user = _context.User.Where(u => u.Token == request.Token).FirstOrDefault<User>();
if (user == null) {
var error = new string[] {"You have to be connected to create a deck!"};
BadRequest(new { errors = new { success = error } });
}
List<DeckCard> deckList = new List<DeckCard>();
if (ModelState.IsValid) {
request.Deck.User = user;
foreach (var item in request.Cards)
{
Card card = _context.Card.FirstOrDefault(c => c.Name == item.Name);
if (card == null) {
card = item;
Console.WriteLine("coucou");
}
DeckCard deckCard = new DeckCard {
Card = card,
Deck = request.Deck
};
deckList.Add(deckCard);
}
_context.DeckCard.AddRange(deckList);
_context.SaveChanges();
var error = new string[] {"Your deck has been successfully saved."};
return Ok(new { errors = new { success = error } });
}
return BadRequest(ModelState.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
));
}

MVC one to many user companies and notifiaction

I have three tables. Users Notification and Company. I have to made relation one to many which one user can have many notification from company. Notification have to be seen only for users from this company. Example users A company B can see notification only from company B not from the others. How to create query and check user which is actually logged in? Can you help me? I show the code.
[Table("Core.Powiadomienias")]
public class Powiadomienia : Entity
{
public string Tytul { get; set; }
public string Tresc { get; set; }
public long? Firma { get; set; }
public ICollection<User> Users { get; set; }
}
public class User : Entity, IUserIdentity, IAuditable, ILoggable,
IConfidential
{
#region User()
public User()
{
LockoutEnabled = true;
Roles = new List<Role>();
}
#endregion
public Guid PublicId { get; set; }
public DateTime DateCreatedUtc { get; set; }
public DateTime? DateModifiedUtc { get; set; }
public long CreatedBy { get; set; }
public long? ModifiedBy { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTime? LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public bool IsAdmin { get; set; }
public string RolesGroupsXml { get; set; }
public string GivenName { get; set; }
public string Surname { get; set; }
public string JobPosition { get; set; }
public string HomeCity { get; set; }
public string HomeStreet { get; set; }
public string HomeHouseNo { get; set; }
public string HomeFlatNo { get; set; }
public string HomePostCode { get; set; }
public string HomeCountry { get; set; }
public long? FacePictureId { get; set; }
public virtual File FacePicture { get; set; }
public long? FirmaId { get; set; }
public Powiadomienia Powiadomienia { get; set; }
#region GetList()
public static IEnumerable<TResult> GetList<TResult>(IPager pager, string
tytul , string tresc = null, long? firma = null)
{
using (var context = Context.Read())
{
Slave db = new Slave();
var query = context.Query<Powiadomienia>().AsQueryable();
if (!String.IsNullOrEmpty(tytul))
{
query = query.Where(p => p.Tytul.Contains(tytul));
}
if (!String.IsNullOrEmpty(tresc))
{
query = query.Where(p => p.Tresc.Contains(tytul) &&
db.Firmy.Select(x => x.Nazwa).Equals(p.Firma));
}
if (firma.HasValue)
{
var value = String.Format("<item>{0}</item>", firma);
query = query.Where(p => p.Firma.HasValue);
}
return query
.Pager(pager)
.GetResult<TResult>();
}
}
public class UserService
{
#region GetList()
public static IEnumerable<TResult> GetList<TResult>(IPager pager, string
userName = null, string givenName = null, string surname = null, long? role
null, bool? isAdmin = null, long? firmaid = null)
{
using (var context = Context.Read())
{
var query = context.Query<User>().AsQueryable();
if (!String.IsNullOrEmpty(userName))
{
query = query.Where(p => p.UserName.Contains(userName));
}
if (!String.IsNullOrEmpty(givenName))
{
query = query.Where(p => p.GivenName.Contains(givenName));
}
if (!String.IsNullOrEmpty(surname))
{
query = query.Where(p => p.Surname.Contains(surname));
}
if (firmaid.HasValue)
{
var value = String.Format("<item>{0}</item>", firmaid.Value);
query = query.Where(p => p.FirmaId.HasValue);
}
if (isAdmin.HasValue && isAdmin.Value == true)
{
query = query.Where(p => p.IsAdmin == true);
}
return query
.Pager(pager)
.GetResult<TResult>();
}
}
#endregion

Insert multiple values from text box to the data base using the list<string>

This is the required image, I want to insert multiple value through Name, Employee Code and E-mail Id, by submit button which is in this page.
My database contains following field Id(primary key),Name (varchar 50),Employee Code (varchar 50), E-mail Id (varchar 50).
In the data layer, I code as following:
public static bool AddParticipantlistemployeecode(DimensionQuestion dimension)
{
bool result;
using (var helper = new DbHelper())
{
_cmdtext = "sp_NewGeneratedUniqueCode";
var success = new SqlParameter("#Success", SqlDbType.Bit, 1, ParameterDirection.Output, true, 0, 0,
"Result", DataRowVersion.Default, 0);
foreach (string s in dimension.CandidateName)
{
if (s.Trim().Length > 0)
{
var parameter = new[]
{
// new SqlParameter("#CompanyName",dimension.CompanyName ),
new SqlParameter("#CandidateName",s ),
new SqlParameter("#EmployeeCode",s ),
new SqlParameter("#EmailId",s ),
success,
};
helper.ExecuteScalar(_cmdtext, CommandType.StoredProcedure, parameter);
}
}
result = (bool)success.Value;
}
return result;
}
In the Model layer:
using System.Text;
using System.Collections.Generic;
namespace Cengrow.Survey.Core.Model
{
public class DimensionQuestion
{
public string CompanyName { get; set; }
// public string DimensionNumber { get; set; }
public List<string> CandidateName { get; set; }
public List<string> EmployeeCode { get; set; }
public List<string> EmailId { get; set; }
public int DimensionName { get; set; }
public string Section { get; set; }
//public string Rating { get; set; }
public List<string> Questions { get; set; }
//public string Question2 { get; set; }
//public string Question3 { get; set; }
//public string Question4 { get; set; }
//public string Question5 { get; set; }
//public string Question6 { get; set; }
//public string Question7 { get; set; }
//public string Question8 { get; set; }
//public string Question9 { get; set; }
//public string Question10 { get; set; }
//public string Question11 { get; set; }
//public string Question12 { get; set; }
//public string Question13 { get; set; }
//public string Question14 { get; set; }
//public string Question15 { get; set; }
}
}
And finally in the business logic on the button click:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
FillObjects();
//if (InsertData.InsertCandidateCompany(_CandidateCompanyInformation ))
if (InsertData.AddParticipantlistemployeecode(_DimensionQuestion))
{
ShowMessage("Information is saved");
//Reset();
}
else
{
ShowMessage("Please try again");
}
}
finally
{
_DimensionQuestion = null;
}
}
private void FillObjects()
{
List<string> sp = new List<string>();
_DimensionQuestion = new Cengrow.Survey.Core.Model.DimensionQuestion();
// _DimensionQuestion.CompanyName = txtCompanyName.Text.Trim();
sp.Add(txtName1.Text.Trim());
sp.Add(txtName2.Text.Trim());
sp.Add(txtName3.Text.Trim());
sp.Add(txtName4.Text.Trim());
sp.Add(txtName5.Text.Trim());
sp.Add(txtName6.Text.Trim());
sp.Add(txtName7.Text.Trim());
sp.Add(txtName8.Text.Trim());
sp.Add(txtName9.Text.Trim());
sp.Add(txtName10.Text.Trim());
sp.Add(txtName11.Text.Trim());
sp.Add(txtName12.Text.Trim());
sp.Add(txtName13.Text.Trim());
sp.Add(txtName14.Text.Trim());
sp.Add(txtName15.Text.Trim());
sp.Add(txtName16.Text.Trim());
sp.Add(txtName17.Text.Trim());
sp.Add(txtName18.Text.Trim());
sp.Add(txtName19.Text.Trim());
sp.Add(txtName20.Text.Trim());
sp.Add(txtName21.Text.Trim());
sp.Add(txtName22.Text.Trim());
sp.Add(txtName23.Text.Trim());
sp.Add(txtName24.Text.Trim());
sp.Add(txtName25.Text.Trim());
_DimensionQuestion.CandidateName = sp;
sp.Add(txtEmployeeCode1.Text.Trim());
sp.Add(txtEmployeeCode2.Text.Trim());
sp.Add(txtEmployeeCode3.Text.Trim());
sp.Add(txtEmployeeCode4.Text.Trim());
sp.Add(txtEmployeeCode5.Text.Trim());
sp.Add(txtEmployeeCode6.Text.Trim());
sp.Add(txtEmployeeCode7.Text.Trim());
sp.Add(txtEmployeeCode8.Text.Trim());
sp.Add(txtEmployeeCode9.Text.Trim());
sp.Add(txtEmployeeCode10.Text.Trim());
sp.Add(txtEmployeeCode11.Text.Trim());
sp.Add(txtEmployeeCode12.Text.Trim());
sp.Add(txtEmployeeCode13.Text.Trim());
sp.Add(txtEmployeeCode14.Text.Trim());
sp.Add(txtEmployeeCode15.Text.Trim());
sp.Add(txtEmployeeCode16.Text.Trim());
sp.Add(txtEmployeeCode17.Text.Trim());
sp.Add(txtEmployeeCode18.Text.Trim());
sp.Add(txtEmployeeCode19.Text.Trim());
sp.Add(txtEmployeeCode20.Text.Trim());
sp.Add(txtEmployeeCode21.Text.Trim());
sp.Add(txtEmployeeCode22.Text.Trim());
sp.Add(txtEmployeeCode23.Text.Trim());
sp.Add(txtEmployeeCode24.Text.Trim());
sp.Add(txtEmployeeCode25.Text.Trim());
_DimensionQuestion.EmployeeCode = sp;
sp.Add(TextBox1.Text.Trim());
sp.Add(TextBox2.Text.Trim());
sp.Add(TextBox3.Text.Trim());
sp.Add(TextBox4.Text.Trim());
sp.Add(TextBox5.Text.Trim());
sp.Add(TextBox6.Text.Trim());
sp.Add(TextBox7.Text.Trim());
sp.Add(TextBox8.Text.Trim());
sp.Add(TextBox9.Text.Trim());
sp.Add(TextBox10.Text.Trim());
sp.Add(TextBox11.Text.Trim());
sp.Add(TextBox12.Text.Trim());
sp.Add(TextBox13.Text.Trim());
sp.Add(TextBox14.Text.Trim());
sp.Add(TextBox15.Text.Trim());
sp.Add(TextBox16.Text.Trim());
sp.Add(TextBox17.Text.Trim());
sp.Add(TextBox18.Text.Trim());
sp.Add(TextBox19.Text.Trim());
sp.Add(TextBox20.Text.Trim());
sp.Add(TextBox21.Text.Trim());
sp.Add(TextBox22.Text.Trim());
sp.Add(TextBox23.Text.Trim());
sp.Add(TextBox24.Text.Trim());
sp.Add(TextBox25.Text.Trim());
_DimensionQuestion.EmailId = sp;
}
The data is not coming proper into the database
You are adding the same value to all three parameters:
new SqlParameter("#CandidateName",s ),
new SqlParameter("#EmployeeCode",s ),
new SqlParameter("#EmailId",s
In all cases you are adding "s" which is CandidateName.
Edit: Candidate should be a class:
public class Candidate
{
public string Name { get; set; }
public string EmployeeCode { get; set; }
public string Email { get; set; }
public Candidate(string name, string code, string email)
{
this.Name = name;
this.EmployeeCode = code;
this.Email = email;
}
}
Then your DimensionQuestion should contain a
List<Candidate> Candidates
instead of
public List<string> CandidateName { get; set; }
public List<string> EmployeeCode { get; set; }
public List<string> EmailId { get; set; }
Then you FillObjects method add Candidate objects to the Candidates list
Candidates.Add(new Candidate(txtName1.Text.Trim(),
txtEmployeeCode1.Text.Trim(),
TextBox1.Text.Trim()));
Candidates.Add(new Candidate(txtName2.Text.Trim(),
txtEmployeeCode2.Text.Trim(),
TextBox2.Text.Trim()));
Finaly your data layer should be:
foreach (Candidate candidate in dimension.Candidates)
{
if (!String.IsNullOrEmpty(candidate.Name))
{
var parameter = new[]
{
// new SqlParameter("#CompanyName",dimension.CompanyName ),
new SqlParameter("#CandidateName",candidate.Name ),
new SqlParameter("#EmployeeCode",candidate.Code ),
new SqlParameter("#EmailId",candidate.Email ),
success,
};
helper.ExecuteScalar(_cmdtext, CommandType.StoredProcedure, parameter);
}
}

Resources