c# - Code First Entity Framework Virtual and Foreign Key Confusions -


so have poco classes:

public class device : dbentity {   public string devicename {get;set;} } public class aut : dbentity {   public string applicationname {get;set;} } public class setup : deviceappdbentity {   public bool worked {get;set;} }  public class dbentity {   public guid id {get;set;} } public class deviceappdbentity : dbentity {   public virtual aut applicationundertesting {get;set;}   public virtual device deviceundertesting {get;set;} } 

so if want delete aut (application) error because setup has foreign key app. i've been told if add

public class deviceappdbentity : dbentity {   public virtual aut applicationundertesting {get;set;}   public guid applicationundertestingid {get;set;} // line added    public virtual device deviceundertesting {get;set;} } 

then cascade delete enabled. correct?

when access setups

_repository.setups.firstordefault(x => x.id.equals(setupid)); 

the navigation property virtual aut & virtual device should automatically filled out?? guid applicationundertestingid automatically filled out?

when want save setup entity, can fill out nav property? or have fill out guid applicationundertestingid field well, or do reverse , fill out guid applicationundertestingid?

entitytosave.aut = _repository.auts.firstordefault(x => x.id.equals(vm.appid)); 

or

entitytosave.applicationundertestingid= vm.appid; entitytosave.aut = _repository.auts.firstordefault(x => x.id.equals(vm.appid)); 

or

entitytosave.applicationundertestingid= vm.appid; 

this kinda confusing.. gets worse when define list<entities>, because when delete entity contains list. complains entities within list having relationships, how enable cascade delete on these?

public class blog: dbentity {   public string name {get;set;}   public virtual member {get;set;}    public list<comment> comments {get;set;} } 

i know seems lot of questions, revolves around 1 topic in entity framework.thank anytime spent answering questions.

to answer this.

cascade on delete enable when navigation properties such as

public virtual someclass {get;set;} public guid someclassid {get;set;} 

you can fill out either of them , save database.

no cascade on delete

public virtual someclass someclass {get;set;} 

when read database mine below:

var item = _repository.someclasses.firstordefault(x => x.id.equals(id)); 

the navigation properties filled out when want access them, lazy loading, because used keyword virtual

as far list<post> goes, if do:

public class post {     public virtual blog blog {get;set;}     public guid blogid {get;set;} } 

then when blog deleted, posts associated deleted. haven't tried see happens if remove blogid, i'm guessing, when delete blog none of posts deleted. blog => post model isn't model demonstrate why want though.

i think have answered questions. sum though, depends on public guid someclassid {get;set;} whether cascade on delete set or not.


Comments