c# - ForeignKey using ASP.NET MVC 4 Migration Code first -
how create foreign key below user
class on id of computer class?
user table:
[table("user")] class user{ [key] public int iduser; public int idcomputer; //foreignkey }
computer table:
[table("computer")] class computer{ [key] public int idcomputer; }
how one-to-many relationship , one-to-one relationship between these classes, please?
to set user has many computers , computer has 1 user, this:
class user { public int iduser {get;set;} public virtual icollection<computer> computers {get;set;} } class computer { public int idcomputer {get;set;} public int userid {get;set;} // automatically detected foreignkey since format [classname]id public virtual user user {get;set;} }
to set computer has many users , user has 1 computer, do:
class user { public int iduser {get;set;} public int computerid {get;set;} public virtual computer computer {get;set;} } class computer { public int idcomputer {get;set;} public virtual icollection<user> users {get;set;} }
to set user has 1 computer:
class user { public int id {get;set;} public virtual computer computer {get;set;} } class computer { public int id {get;set;} [required] public int userid {get;set;} public virtual user user {get;set;} }
the [required]
tag should eliminate errors one-to-one relationship
as side note, whole point of ef code first make things super simple , quick , easy, when don't use of features offers diminishes , have more manual work, can lead mistakes.
here's tutorial on how code-first. recommend read on it.
okay, re-read original question. can't have both (one-to-one , one-to-many) between same 2 classes, can either have one-to-one (i.e., user has 1 computer , computer has 1 user) or one-to-many (i.e, user has many computers , computer has 1 user, or computer has many users , user has 1 computer.) it's 1 or other, not both, kind of thing. fact think possible reinforces statement really need read tutorial or read on simple relational database structure
Comments
Post a Comment