Creating a ManyToMany relationship between two models - c#

I'm new to creating a Windows Store app and it requires a use of a database. I've settled for sqlite and am using the sqlite-net package. However, I'm unsure of how to create a m2m relationship between two models.
class ModelA
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string name { get; set; }
<relationship to ModelB>
}
class ModelB
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string name { get; set; }
}
Would I have to use a List? or a byte[]? How can I guarantee the property will be constrained to ModelB?

You might be able to use sqlite-net-extensions, it has a ManyToMany attribute that seems perfect for your needs. This is an example of its use from their website.
public class Student
{
[PrimaryKey, AutoIncrement]
public int StudentId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
[ManyToMany(typeof(StudentsGroups))]
public List<Group> Groups { get; set; }
public int TutorId { get; set; }
[ManyToOne("TutorId")] // Foreign key may be specified in the relationship
public Teacher Tutor { get; set; }
}
public class Group
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string GroupName { get; set; }
[ForeignKey(typeof(Teacher))]
public int TeacherId { get; set; }
[ManyToOne]
public Teacher Teacher { get; set; }
[ManyToMany(typeof(StudentsGroups))]
public List<Student> Students { get; set; }
}
public class StudentGroups
{
[ForeignKey(typeof(Student))]
public int StudentId { get; set; }
[ForeignKey(typeof(Group))]
public int GroupId { get; set; }
}

Related

One to many relationship with code first. Where this foreign-key came from?

My data class is
public class Data
{
public int Id { get; set; }
public int LeagueId { get; set; }
public League League { get; set; }
public int HomeTeamId { get; set; }
public virtual Team HomeTeam { get; set; }
public int AwayTeamId { get; set; }
public virtual Team AwayTeam { get; set; }
}
and my team class is
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Data> Datas { get; set; }
}
which generates an extra foreign key FK_dbo.Data_dbo.Teams_Team_Id and also and extra column in my Data table.
So my first question is, how that foreign-key was created there?
Can i have two one to many relationships that target at the same table with entity framework?
I need to set both the HomeTeamId and the AwayTeamId in the Data table as one to many relationship
Try:
public class Data
{
public int Id { get; set; }
public int LeagueId { get; set; }
[ForeignKey("LeagueId")] /* Add explicit foreign key data annotations */
public League League { get; set; }
public int HomeTeamId { get; set; }
[ForeignKey("HomeTeamId")]
public virtual Team HomeTeam { get; set; }
public int AwayTeamId { get; set; }
[ForeignKey("AwayTeamId")]
public virtual Team AwayTeam { get; set; }
}
public class Team
{
public Team()
{
this.HomeTeamData = new HashSet<Data>();
this.AwayTeamData = new HashSet<Data>();
}
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("HomeTeam")]
public virtual ICollection<Data> HomeTeamData { get; set; }
[InverseProperty("AwayTeam")]
public virtual ICollection<Data> AwayTeamData { get; set; }
}
Let me know if this helps.
I suspect you may be hitting the limit of Entity's ability to figure out what you want. You may need to consider using some Entity Annotations to instruct Entity on what you want it to actually do.

Getting more column using foreign key possible?

I'm new to ASP.NET MVC and I have been trying to create a school application in which I have these three classes:
public class student
{
public int id { get; set; }
public string name { get; set; }
}
public class subject
{
public int id { get; set; }
public int Math { get; set; }
public int Computer { get; set; }
public int Chemistry { get; set; }
}
public class result
{
public int id { get; set; }
public int studentId { get; set; }
public int subjectId { get; set; }
public int Total { get; set; }
public virtual student students { get; set; }
public virtual subject subjects { get; set; }
}
I want to get all the properties of subject in result like math, computer, chemistry and so I can edit, create or delete them in result page.
Can somebody point me to any tutorial or help me with this?
A good starting point could be
here

Many to Many Relationship with extra columns in EF 6 Code?

Say if I have the classic example of Student and Courses. A student can have many courses and course can have many students.
How do I make the middle table in EF 6 code if I wanted to add an extra field on the many table part?
Do I just make in code another class and then hook it up somehow?
DB Context
public class MyContext : DbContext
{
public MyContext (string nameOrConnectionString) : base(nameOrConnectionString)
{
// this.Configuration.ProxyCreationEnabled = false;
Database.SetInitializer(new CreateDatabaseIfNotExists<OSPContext>());
}
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<StudentCourse> StudentCourses { get; set; }
}
public class StudentCourse
{
[Key]
public Guid StudentCourseId { get; set; }
public Guid StudentId { get; set; }
[ForeignKey("StudentId")]
public virtual Student Student { get; set; } // Include this so you can access it later
public Guid CourseId { get; set; }
[ForeignKey("CourseId")]
public virtual Course Course { get; set; }
public int Permissions { get; set; }
}
public class Course
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; } = new >();
}
public class Student
{
[Key]
public Guid Id { get; set; }
public string Email { get; set; }
public virtual ICollection<Course> Courses { get; set; } = new List<Course>();
}
Given you are code first I would do something like the following.
public class Student
{
[Key]
public int StudentId { get; set; }
public string Name { get; set; }
public List<StudentCourse> Courses { get; set; } // So you can access Courses for a student
}
public class Course
{
[Key]
public int CourseId { get; set; }
public string Name { get; set; }
public List<StudentCourse> Students { get; set; }
}
public class StudentCourse
{
[Key]
public int StudentCourseId { get; set; }
public int StudentId { get; set; }
[ForeignKey("StudentId")]
public Student Student { get; set; } // Include this so you can access it later
public int CourseId { get; set; }
[ForeignKey("CourseId")]
public Course Course { get; set; }
}
EDIT: Wanted to note relationships are established with Data Attributes, you could also use EF Fluent API to establish your relationships. The properties will look the same, but without the [ForeignKey("")]

Asp.net mvc 4 foreign key in models

I have these tables:
public class udb:DbContext
{
public DbSet<klasa> Keuni { get; set; }
public DbSet<student> Seuni { get; set; }
}
public class student
{
[Key]
public int studentid { get; set; }
public string emristudent { get; set; }
public int nota { get; set; }
[ForeignKey("klasaid"), Column(Order = 0)]
public int klasaid { get; set; }
}}
public class klasa
{ [Key]
public int klasaid { get; set; }
public string emriklases { get; set; }
public string vendodhja { get; set; }
public virtual ICollection<student> students { get; set; }
}
The problem is that I want the klasaid to be a foreign key in students so when the user adds a new student the klasaid should exist in klasa model.I use Asp.net mvc 4.Can sb help me?
It should look like this:
public class student
{
[Key]
public int studentid { get; set; }
public string emristudent { get; set; }
public int nota { get; set; }
public int klasaid {get;set;}
[ForeignKey("klasaid")]
public klasa Klasa{ get; set; }
}
You can use various database initialization strategies as follows:
public class udb:DbContext
{
public udb()
{
Database.SetInitializer<udb>(new CreateDatabaseIfNotExists<udb>());
}
public DbSet<klasa> Keuni { get; set; }
public DbSet<student> Seuni { get; set; }
}
One suggestion- follow proper naming conventions. Please, have a look into this link for more details.

Entity Framework Code First Relationships

I'm learning EF using Code First and I'm having a lot of trouble getting my relationships to build correctly.
A Simple Employee
public class Employee
{
[Key]
public int EmployeeId { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
}
A Simple Project
public class Project
{
[Key]
public int ProjectId { get; set; }
public String ProjectNumber { get; set; }
}
The time spent on the project
public class Time
{
[Key]
public int TimeId { get; set; }
public int EmployeeID { get; set; }
public String ProjectID { get; set; }
public long? TimeSpent { get; set; }
public virtual Employee Employee { get; set; }
public virtual Project Project { get; set; }
}
I'm trying to join Employee to Time on EmployeeID and join Project to Time on ProjectID and I just don't understand how EF determines relationships. I'm trying to use Data Annotations to define the relationships. I've tried using the ForeignKey annotation to define the relationships but that has not worked either.
What I have will run, but on the Project table, a new field named Project_ProjectID is created and if I try to run a query in VS I get an error saying that the column Time_TimeID is invalid (which it is). What am I doing wrong?
You shouldn't need DataAnnotations as conventions will work for you in this case
Try the following
public class Time
{
[Key]
public int TimeId { get; set; }
public int EmployeeID { get; set; }
public int ProjectID { get; set; } //<< Changed type from string
public long? TimeSpent { get; set; }
public virtual Employee Employee { get; set; }
public virtual Project Project { get; set; }
}
public class Employee
{
[Key]
public int EmployeeId { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
// Set up the other side of the relationship
public virtual ICollection<Time> Times { get; set; } // << Added
}
public class Project
{
[Key]
public int ProjectId { get; set; }
public String ProjectNumber { get; set; }
// Set up the other side of the relationship
public virtual ICollection<Time> Times { get; set; } // << Added
}
This article may help
http://msdn.microsoft.com/en-gb/data/jj679962.aspx

Categories