I've just started using Linq and at the moment I've got a database ready and made some entity classes in C#.
Now my object called "Person" has a many-to-many relationship with "Profession." But whenever I try to call out the next statement it won't work:
Context ctx = new Context(ConfigurationManager.ConnectionStrings["myContext"].ConnectionString);
var Julian = (from j in ctx.persons
where j.Name == "Julian"
select j).Single();
Profession proftest = new Profession() { Name = "Programmer", Accepted = true };
Julian.Professesions.Add(proftest);
ctx.SubmitChanges();
Now I'll show you the classes that I'm working with:
Person got the next few things (the rest of the class variable works so I'll show you the bad part):
// Data (for mapping)
private EntitySet<PersonProfession> personProfession;
public Person()
{
personProfession = new EntitySet<PersonProfession>();
}
[Association(Name = "FK_j_Person_Profession_Person", Storage = "personProfession", OtherKey = "personId", ThisKey = "Id")]
internal ICollection<PersonProfession> PersonProfessions
{
get { return personProfession; }
set { personProfession.Assign(value); }
}
public ICollection<Profession> Professions
{
get { return (from prof in PersonProfessions where prof.Profession.Accepted==true select prof.Profession).ToList(); }
}
Now I am able to call the following method in the "Person" class with success:
public void AddProfession(Profession profession, Person person)
{
PersonProfession pp = new PersonProfession();
pp.Person = person;
pp.Profession = profession;
personProfession.Add(pp);
}
But ofcourse that's not what I want.
The data relation is like this:
Person --> j_Person_Profession <-- Profession
I've also got the same problem (that the .Add() wont work) with another relation between Person and Alias (which is a table with only an int for PersonId and a String for alias.
Last little question is the following: My "Profession" class also got the same link with "Person", so whenever I ask the context for a person, I can look at his/her profession and within the profession there are more Persons with the same profession. Isn't this very slow with big databases? Maybe I should remove the backward link?
From Yakimych's comment, I got my answer:
it's Linq-to-SQL you are using, aren't you? AFAIK, L2S maps the junction table as an entity, so you have to use the
PersonProfessionobject as you do in your working example. In case of Entity Framework as opposed to L2S, a pure junction table (containing only the two foreign keys) would not be mapped to a separate entity, and you could accessPerson.ProfessionsandProfessions.Peopledirectly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With