hi i am having an issue to update related data - c#

I am trying to add a member to a group in my application, I need be able to add one or more members to a group. Please can you assist?
below are my classes
public class member
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int memberid { get; set;}
[Required]
[Display(Name ="first name")]
public string membername { get; set; }
[Required]
[Display(Name = "last name")]
public string memberlastname { get; set;}
[Required]
[Display(Name = "email address")]
[DataType(DataType.EmailAddress)]
public string email { get; set; }
public int groupid { get; set; }
public virtual group groups { get; set; }
}
and
public class group
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int groupid { get; set; }
[Required]
[Display(Name = "group name")]
public string groupname { get; set; }
public IEnumerable<member> members { get; set; }
}

One way would be to change the data type of your group.members property from an IEnumerable<member> to a List<member>:
public class group
{
// Other properties not shown
public List members { get; set; }
}
Then you could just call the Add method:
static void Main()
{
group g = new group();
member m = new member();
g.members.Add(m);

Related

One to Many and a Many to Many relationship Entity Framework including default Authorization and role managing

I have a system that produce some online classes. In this class we have students and a teacher.
I have used Microsoft default Identity System and Authorization for this system, but something is bothering me in my design.
For more explanation I want to define Roles(Teacher, Students, Admins and etc) , but it is so confusing how to handle relation between Course and Teacher (it is one to many relation) and Course to Students (it has many to many relation).
So I have question is that true way to have two relation between two entities or not? if it is not, How should I handle this?
Here is my Course entity
[Key]
[Display(Name = "شناسه")]
public Guid CourseId { get; set; }
[Required]
[Display(Name = "لوگوی دوره")]
public string LogoPath { get; set; }
[Required]
[Display(Name = "نام دوره")]
public string Name { get; set; }
[Required]
[Display(Name = "شرح دوره")]
public string Description { get; set; }
[Required]
[Display(Name = "شهریه")]
public int Price { get; set; }
[Display(Name = "دارای تخفیف")]
public bool HasDiscount { get; set; }
[Display(Name = "درصد تخفیف")]
public float DiscountPercentage { get; set; }
[Required]
[Display(Name = "آخرین تاریخ به روزرسانی")]
public DateTime LastUpdateUpdate { get; set; }
public string UserId { get; set; }
public AppUser CourseTeacher { get; set; }
public Guid CaptionId { get; set; }
public MainCaption CourseCaption{ get; set; }
public ICollection<Chapter> Chapters { get; set; }
public ICollection<AppUser> Students{ get; set; }
and here is my AppUser entity
[Required]
[Display(Name = "نام")]
public string Firstname { get; set; }
[Required]
[Display(Name = "نام خانوادگی")]
public string LastName { get; set; }
[Required]
[Display(Name = "جنسیت")]
public Gender Gender { get; set; }
[Display(Name = "عنوان")]
public string Title { get; set; }
[Display(Name = "اعتبار")]
public int Credit { get; set; }
[Display(Name = "تاریخ تولد")]
public string BirthDate { get; set; }
[Display(Name = "مدرک تحصیلی")]
public EducationalDegree? Degree { get; set; }
[Display(Name = "آدرس تصویر")]
public string ImagePath { get; set; }
[Display(Name = "تصویر تایید شده")]
public bool? IsImageConfirmed { get; set; }
[Display(Name = "آدرس فیس بوک")]
public string Facebook { get; set; }
[Display(Name = "آدرس اینستاگرام")]
public string Instagram { get; set; }
[Display(Name = "آدرس لینکداین")]
public string Linkedin { get; set; }
[Display(Name = "آدرس توئیتر")]
public string Twitter { get; set; }
[Display(Name = "آدرس وبسایت")]
public string Website { get; set; }
[Display(Name = "تاریخ ثبت نام")]
public DateTime RegisterDate { get; set; }
public ICollection<Course> StudentCourses { get; set; }
public ICollection<Course> TeacherCourses { get; set; }
public ICollection<News> WrittenNews { get; set; }
Tnx to All
Edit
I forgot to say this contains an error Sequence contains more than one matching element and it seems logical
One important this is that if I use same class for inheritance how should I add two relations for this two tables AppUser and Course
I want to define Roles(Teacher, Students, Admins and etc)
You can do it in a couple different ways:
Have User and Role tables and enforce roles on the application level, e.g. Only "teacher" user can do teacher things, only student can enrol into courses etc.
With EF you can use inheritance. Abstract User would have all the common fields and Student, Teacher and Admin would have fields specific only to their role.
Please see the code:
abstract class User
{
public int UserId { get; set; }
public string Name { get; set; }
}
class Teacher : User
{
public string Specialty { get; set; }
}
class Student : User
{
public int Grade { get; set; }
}
See more info here - the example given in this official documentation is very close to what you're trying to achieve.
Course to Students (it has many to many relation)
For this type of a relationship I'd create a new table/entity StudentCourse with composite (StudentId, CourseId) key. And the reason for it is, usually you don't just want a link between 2 entities but also to keep some additional info like Mark, Performance or EnrolmentDate:
class StudentCourse
{
public int StudentId { get; set; }
public int CourseId { get; set; }
public Student Student { get; set; }
public Course Course { get; set; }
// Any additional fields related to the relationship
public int Mark { get; set; }
}

Entity Framework : two inner joins on the same table

I have the following database schema and relation
What I'm trying to do is to select from the ProductActiveIngredient table with the known of productId, and I want to select every ActiveIngredientOne, ActiveIngredientTwo, ActiveIngredientThree, and ActiveIngredientFour from inner joining the ActiveIngredient table with ProductActiveIngredient.
Executing this query will return each ActiveIngredientOne, and ActiveIngredientTwo columns name:
select
a.ActiveIngredientOne, b.ActiveIngredientName, c.ActiveIngredientName
from
ProductActiveIngredient a
inner join
ActiveIngredient b on a.ActiveIngredientOne = b.ActiveIngredientId
inner join
ActiveIngredient c on a.ActiveIngredientTwo = c.ActiveIngredientId
and the query result is:
query result
What I want to do is to make this query using Entity Framework.
I have the following models written in my solution:
public class Product
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string ProductGuid { set; get; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductId { set; get; }
[Required]
[Display(Name = "Cost")]
public int Cost { set; get; }
[Required]
[Display(Name = "Tax")]
public int Tax { set; get; }
[Required]
[Display(Name = "Profit")]
public int Profit { set; get; }
[Required]
[Display(Name = "Discount")]
public int Discount { set; get; }
[Required]
[Display(Name = "Price")]
public int Price { set; get; }
[Required]
[Display(Name = "Units")]
public int Units { set; get; }
[Required]
[Display(Name = "Pack size")]
public int PackSize { set; get; }
[Display(Name = "Description")]
public string Description { set; get; }
[Display(Name = "Manufacturer id")]
public int ManufacturerId { set; get; }
public virtual Contact Contact { set; get; }
public virtual ProductActiveIngredient ProductActiveIngredient { set; get; }
}
public class ProductActiveIngredient
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string ProductActiveIngredientGuid { set; get; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductActiveIngredientId { set; get; }
[Required]
[Display(Name = "Active Ingredient 1")]
public int ActiveIngredientOne { set; get; }
//[Display(Name = "Active Ingredient 2")]
#nullable enable
public int ActiveIngredientTwo { set; get; }
public int ActiveIngredientThree { set; get; }
public int ActiveIngredientFour { set; get; }
#nullable disable
public int ProductId { set; get; }
public int ForUser { set; get; }
public virtual Product Product { set; get; }
public virtual User User { set; get; }
public virtual ActiveIngredient ActiveIngredient { set; get; }
}
public class ActiveIngredient
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string ActiveIngredientGuid { set; get; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ActiveIngredientId { set; get; }
[Required]
[Display(Name = "Active ingredient name")]
public string ActiveIngredientName { set; get; }
public virtual ProductActiveIngredient ProductActiveIngredient { set; get; }
}
and this is my db context relation:
modelBuilder.Entity<Product>()
.HasOne(pai => pai.ProductActiveIngredient)
.WithOne(p => p.Product)
.HasForeignKey<ProductActiveIngredient>(p => p.ProductActiveIngredientId);
modelBuilder.Entity<ActiveIngredient>()
.HasOne(ai => ai.ProductActiveIngredient)
.WithOne(aco => aco.ActiveIngredient)
.HasForeignKey<ProductActiveIngredient>(a => a.ActiveIngredientOne);
modelBuilder.Entity<ActiveIngredient>()
.HasOne(ai => ai.ProductActiveIngredient)
.WithOne(aco => aco.ActiveIngredient)
.HasForeignKey<ProductActiveIngredient>(a => a.ActiveIngredientTwo);
modelBuilder.Entity<ActiveIngredient>()
.HasOne(ai => ai.ProductActiveIngredient)
.WithOne(aco => aco.ActiveIngredient)
.HasForeignKey<ProductActiveIngredient>(a => a.ActiveIngredientThree);
modelBuilder.Entity<ActiveIngredient>()
.HasOne(ai => ai.ProductActiveIngredient)
.WithOne(aco => aco.ActiveIngredient)
.HasForeignKey<ProductActiveIngredient>(a => a.ActiveIngredientFour);
This LinQ query executes fine, and get the same result as the T-SQL query, but I need to do it in EF not in LinQ:
var s = from pac in _db.ProductActiveIngredient
join ai in _db.ActiveIngredient on pac.ActiveIngredientOne equals ai.ActiveIngredientId
join ai2 in _db.ActiveIngredient on pac.ActiveIngredientTwo equals ai2.ActiveIngredientId
where pac.ProductId == productId
select new
{
pac.ActiveIngredientOne,
ai.ActiveIngredientName,
pac.ActiveIngredientTwo,
b2 = ai2.ActiveIngredientName
};
Any help please?
It's done, Many thanks.
What I did is added another three virtual properties in my ProductActiveIngredient class, and in ActiveIngredient class.
Then i used the .Include(x=>x.ProductActiveIngredientOne)
.ThenInclude(z=>z._ActiveIngredientOne).FirstOrDefaultAsync();
and updated my db context as the properties above.

Confusing to create models class for cascading drop down list using MVC 5 and entity framework code first

Below is my State Model class.
public class State
{
[Key]
public int StateId { get; set; }
public string StateName { get; set; }
public virtual ICollection<City> Cities { get; set; }
}
Below is my City Model Class base state, city will fill.
public class City
{
[Key]
public int CityId { get; set; }
public string CityName { get; set; }
[ForeignKey("State")]
public int StateId { get; set; }
public virtual State State { get; set; }
}
Below is my Registration model class for the registration form which calls State city.
public class Registration
{
[Key]
public int Sno { get; set; }
[Required(ErrorMessage = "Name is required.")]
[Display(Name = "Full name")]
public string Fullname { get; set; }
[Display(Name = "Email Id")]
[Required(ErrorMessage = "Email is required.")]
public string EmailId { get; set; }
[Required(ErrorMessage = "Password is required.")]
public string Password { get; set; }
[Required(ErrorMessage = "Mobile is required.")]
public string Mobile { get; set; }
[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
public int SelectedStateId { get; set; }
public int SelectedCityId { get; set; }
[Required(ErrorMessage = "Entity is required.")]
public string EntityType { get; set; }
public string Website { get; set; }
public string PinCode { get; set; }
public string accountactivated { get; set; }
public int RoleId { get; set; }
[Display(Name = "New Password")]
[NotMapped]
public string NewPassword { get; set; }
[Display(Name = "Confirm New Password")]
[NotMapped] // Does not effect with your database
[System.Web.Mvc.Compare("NewPassword", ErrorMessage = "Password not match")]
public string ConfirmNewPassword { get; set; }
}
My question is how should i have to call state and city cascading drop down list in my Registration Model class to generate scaffolding for registration page with dependent drop down list.

insertion of foreign key asp.net mvc

i have 3 models
public class UsersModel
{
[Key]
public int UserId { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 5", MinimumLength = 5)]
public string Name { get; set; }
//20150090
public int? student_ID { get; set; }
[Display(Name = "transcript")]
public string transcript { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 2", MinimumLength = 2)]
public string Department { get; set; }
[Required]
[Display(Name = "Phone")]
[DataType(DataType.PhoneNumber,ErrorMessage ="Invalid Phone Number")]
[Range(999999999, 9999999999)]
public int Phone { get; set; }
public int type { get; set; }
}
student
public class StudentsModel
{
[Key]
[Display(Name ="ID")]
public int StudentID { get; set; }
[Required]
public string Name { get; set; }
[Required]//20150090
public string student_ID { get; set; }
[Required]
[Display(Name = "Skills")]
public string Skills { get; set; }
[Required]
[Display(Name = "Gpa")]
[Range(1.00, 4.00, ErrorMessage = "It must be in range 0.00 to 4.00 :)")]
public float Gpa { get; set; }
[Required]
[Display(Name = "Leader")]
public string Leader { get; set; }
[Required]
[Display(Name = "transcript")]
public string transcript { get; set; }
[ForeignKey("UserId")]
public int UserId;
public UsersModel Users { get; set; }
[ForeignKey("IdeaId")]
public int? IdeaId;
public IdeaModel Idea { get; set; }
}
Idea
public class IdeaModel
{
[Required]
[Key]
public int IdeaId { get; set; }
[Required]
public string IdeaName { get; set; }
[Required]
public string IdeaDescription { get; set; }
[Required]
public string tools { get; set; }
public int? SetWith { get; set; }
[Required]
public int Prof1 { get; set; }
public int Prof2 { get; set; }
public int Prof3 { get; set; }
}
when i insert to the database user and student and idea
the foreign key in student model inserted with null value
this is the code for insertion
i want the foreign key in student model to inserted automatically
whit the values of primary key in usernodel and idea model how to make this?
public ActionResult RegisterLeader(regall reg)
{
if (ModelState.IsValid)
{
var user= db.Users.Add(reg.users);
var idea = db.Idea.Add(reg.idea);
var stu = db.Students.Add(reg.students[0]);
db.SaveChanges();
return View("RegisterLeaderPost");
//return Registerfinish();
}
}
this model have the three models
public class regall
{
public List<StudentsModel> students { get; set; }
public UsersModel users { get; set; }
public IdeaModel idea { get; set; }
}
You need to set the Idea property of the student so EF knows to make the relationship.
reg.students[0].Idea = reg.idea;

Invalid column name when inserting - Entity Framework

I'm using Entity framework using code first. I have 3 tables in database:
Place
Profil
PlaceMember
It's a many to many relation. A place can have many Profils as members and a profil can be a member to many Places. The PlaceMember is the relational table.
Code of PlaceDTO:
[Table("Place")]
public partial class PlaceDTO
{
public PlaceDTO()
{
Members = new HashSet<ProfilDTO>();
}
public int id { get; set; }
[StringLength(100)]
public string description { get; set; }
public DateTime dateOut { get; set; }
public DateTime createDate { get; set; }
public int? canceled { get; set; }
public int profilId { get; set; }
public int addressId { get; set; }
public virtual AddressDTO Address { get; set; }
public virtual ProfilDTO Profil { get; set; }
public virtual ICollection<ProfilDTO> Members { get; set; }
}
Code of Profil class:
public partial class ProfilDTO
{
public ProfilDTO()
{
Devices = new HashSet<DeviceDTO>();
Notifications = new HashSet<NotificationDTO>();
Places = new HashSet<PlaceDTO>();
}
public int id { get; set; }
[Required]
[StringLength(50)]
public string pseudo { get; set; }
[Required]
[StringLength(50)]
public string firstname { get; set; }
[Required]
[StringLength(50)]
public string lastname { get; set; }
[Required]
[StringLength(15)]
public string phone { get; set; }
[Required]
[StringLength(50)]
public string emailAdresse { get; set; }
[Required]
[StringLength(150)]
public string password { get; set; }
public DateTime lastUpdatePassword { get; set; }
public DateTime lastUpdateProfil { get; set; }
public DateTime createDate { get; set; }
public byte[] picture { get; set; }
public virtual ICollection<PlaceDTO> Places { get; set; }
}
Code of PlaceMember class:
[Table("PlaceMember")]
public partial class PlaceMemberDTO
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int placeId { get; set; }
[Key]
[Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int invitedId { get; set; }
}
In database, the placeId and invitedId are both identity key of the table.
When I'm trying to add a new place to the Place table, I'm getting that PlaceDTO_id is not a valid column name despite the fact that the place table in database has an column named id and is the identity column.
context.Address.Attach(place.Address);
context.Address.Add(place.Address);
place.addressId = place.Address.id;
context.Places.Attach(place);
context.Places.Add(place);
context.SaveChanges();
The place object, put in param, contains 3 members that exists in Profil table.
When I remove the Members field from the PlaceDTO table, the place is inserted but nothing added to the PlaceMember table.
What's wrong ?

Categories