Problem using related entities in “database-first” The Next CEO of Stack OverflowEntity Framework vs LINQ to SQLHow can I get Id of inserted entity in Entity framework?Code-first vs Model/Database-firstFastest Way of Inserting in Entity FrameworkValidation failed for one or more entities. See 'EntityValidationErrors' property for more detailsnpgsql and Entity Framework code first setup problemsNull Foreign Key in Entity Framework code firstEntity Framework Code First: The number of properties in the Dependent and Principal Roles in a relationship constraint must be identicalIs it possible to use Entity Framework Core with existing database on tables with no primary key?mvc database-first primary key dont work?
Early programmable calculators with RS-232
What happens if you break a law in another country outside of that country?
Ising model simulation
logical reads on global temp table, but not on session-level temp table
Is a linearly independent set whose span is dense a Schauder basis?
That's an odd coin - I wonder why
Is a distribution that is normal, but highly skewed, considered Gaussian?
Is this a new Fibonacci Identity?
Gödel's incompleteness theorems - what are the religious implications?
Can I cast Thunderwave and be at the center of its bottom face, but not be affected by it?
Is it reasonable to ask other researchers to send me their previous grant applications?
What does this strange code stamp on my passport mean?
Is it a bad idea to plug the other end of ESD strap to wall ground?
Calculating discount not working
Creating a script with console commands
Find the majority element, which appears more than half the time
Prodigo = pro + ago?
How can I replace x-axis labels with pre-determined symbols?
Could a dragon use its wings to swim?
Arrows in tikz Markov chain diagram overlap
How to find if SQL server backup is encrypted with TDE without restoring the backup
Why does freezing point matter when picking cooler ice packs?
Planeswalker Ability and Death Timing
Free fall ellipse or parabola?
Problem using related entities in “database-first”
The Next CEO of Stack OverflowEntity Framework vs LINQ to SQLHow can I get Id of inserted entity in Entity framework?Code-first vs Model/Database-firstFastest Way of Inserting in Entity FrameworkValidation failed for one or more entities. See 'EntityValidationErrors' property for more detailsnpgsql and Entity Framework code first setup problemsNull Foreign Key in Entity Framework code firstEntity Framework Code First: The number of properties in the Dependent and Principal Roles in a relationship constraint must be identicalIs it possible to use Entity Framework Core with existing database on tables with no primary key?mvc database-first primary key dont work?
I am learning MVC and for do this I am developing a "smart forum". I have do a database but I have some problem with entities. I have do this command
"Scaffold-DbContext "Server=(localdb)mssqllocaldb;Database=SmartForum;Trusted_Connection=True; Microsoft.EntityFrameworkCore.SqlServer -OutputDir ModelsFromDb" ,
A code snippet:
modelBuilder.Entity<ArgomentiPerArea>(entity =>
entity.HasKey(e => e.ArgomentoId);
entity.Property(e => e.ArgomentoId).HasColumnName("argomentoId");
entity.Property(e => e.Archiviato).HasColumnName("archiviato");
entity.Property(e => e.AreaId).HasColumnName("areaId");
entity.Property(e => e.ModeratoreId).HasColumnName("moderatoreId");
entity.Property(e => e.NomeArgomento).HasColumnName("nome_argomento");
entity.Property(e => e.NumeroRigaPerArea).HasColumnName("numero_riga_per_area");
entity.Property(e => e.TestoPerArgomento).HasColumnName("testo_per_argomento");
entity.HasOne(d => d.Area)
.WithMany(p => p.ArgomentiPerArea)
.HasForeignKey(d => d.AreaId)
.HasConstraintName("FK_ArgomentiPerArea_Aree");
entity.HasOne(d => d.Moderatore)
.WithMany(p => p.ArgomentiPerArea)
.HasForeignKey(d => d.ModeratoreId)
.HasConstraintName("FK_ArgomentiPerArea_Moderatori");
);
a second snippet :
public partial class ArgomentiPerArea
public ArgomentiPerArea()
Thread = new HashSet<Thread>();
[Key]
public int ArgomentoId get; set;
public string NomeArgomento get; set;
public int? AreaId get; set;
public bool? Archiviato get; set;
public int? NumeroRigaPerArea get; set;
public string TestoPerArgomento get; set;
public int? ModeratoreId get; set;
public virtual Aree Area get; set;
public virtual Moderatori Moderatore get; set;
public virtual ICollection<Thread> Thread get; set;
public partial class Aree
public Aree()
ArgomentiPerArea = new HashSet<ArgomentiPerArea>();
[Key]
public int AreaId get; set;
public string NomeArea get; set;
public int? NumeroRiga get; set;
public int? NumeroColonna get; set;
public virtual ICollection<ArgomentiPerArea> ArgomentiPerArea get; set;
public partial class Moderatori
public Moderatori()
ArgomentiPerArea = new HashSet<ArgomentiPerArea>();
SegnalazioniPerModeratori = new HashSet<SegnalazioniPerModeratori>();
[Key]
public int ModeratoreId get; set;
public string UsernameModeratore get; set;
public string PasswordHash get; set;
public string NomeCognome get; set;
public bool? Archiviato get; set;
public virtual ICollection<ArgomentiPerArea> ArgomentiPerArea get; set;
public virtual ICollection<SegnalazioniPerModeratori> SegnalazioniPerModeratori get; set;
when this code run
public class ArgomentiPerAreasController : Controller
private ModelsFromDb.SmartForumContext db = new ModelsFromDb.SmartForumContext();
// GET: ArgomentiPerAreas
public ActionResult Index()
var argomentiPerAreas = db.ArgomentiPerArea.Include(a => a.Area).Include(a => a.Moderatore);
string msg = "m";
return View(argomentiPerAreas.ToList());
.............
.............
I check in view and "moderatore" and "area" have null value.
I don't understand but I know database first and MVC superficially. I hope in some suggestions.
c# entity-framework ef-database-first
add a comment |
I am learning MVC and for do this I am developing a "smart forum". I have do a database but I have some problem with entities. I have do this command
"Scaffold-DbContext "Server=(localdb)mssqllocaldb;Database=SmartForum;Trusted_Connection=True; Microsoft.EntityFrameworkCore.SqlServer -OutputDir ModelsFromDb" ,
A code snippet:
modelBuilder.Entity<ArgomentiPerArea>(entity =>
entity.HasKey(e => e.ArgomentoId);
entity.Property(e => e.ArgomentoId).HasColumnName("argomentoId");
entity.Property(e => e.Archiviato).HasColumnName("archiviato");
entity.Property(e => e.AreaId).HasColumnName("areaId");
entity.Property(e => e.ModeratoreId).HasColumnName("moderatoreId");
entity.Property(e => e.NomeArgomento).HasColumnName("nome_argomento");
entity.Property(e => e.NumeroRigaPerArea).HasColumnName("numero_riga_per_area");
entity.Property(e => e.TestoPerArgomento).HasColumnName("testo_per_argomento");
entity.HasOne(d => d.Area)
.WithMany(p => p.ArgomentiPerArea)
.HasForeignKey(d => d.AreaId)
.HasConstraintName("FK_ArgomentiPerArea_Aree");
entity.HasOne(d => d.Moderatore)
.WithMany(p => p.ArgomentiPerArea)
.HasForeignKey(d => d.ModeratoreId)
.HasConstraintName("FK_ArgomentiPerArea_Moderatori");
);
a second snippet :
public partial class ArgomentiPerArea
public ArgomentiPerArea()
Thread = new HashSet<Thread>();
[Key]
public int ArgomentoId get; set;
public string NomeArgomento get; set;
public int? AreaId get; set;
public bool? Archiviato get; set;
public int? NumeroRigaPerArea get; set;
public string TestoPerArgomento get; set;
public int? ModeratoreId get; set;
public virtual Aree Area get; set;
public virtual Moderatori Moderatore get; set;
public virtual ICollection<Thread> Thread get; set;
public partial class Aree
public Aree()
ArgomentiPerArea = new HashSet<ArgomentiPerArea>();
[Key]
public int AreaId get; set;
public string NomeArea get; set;
public int? NumeroRiga get; set;
public int? NumeroColonna get; set;
public virtual ICollection<ArgomentiPerArea> ArgomentiPerArea get; set;
public partial class Moderatori
public Moderatori()
ArgomentiPerArea = new HashSet<ArgomentiPerArea>();
SegnalazioniPerModeratori = new HashSet<SegnalazioniPerModeratori>();
[Key]
public int ModeratoreId get; set;
public string UsernameModeratore get; set;
public string PasswordHash get; set;
public string NomeCognome get; set;
public bool? Archiviato get; set;
public virtual ICollection<ArgomentiPerArea> ArgomentiPerArea get; set;
public virtual ICollection<SegnalazioniPerModeratori> SegnalazioniPerModeratori get; set;
when this code run
public class ArgomentiPerAreasController : Controller
private ModelsFromDb.SmartForumContext db = new ModelsFromDb.SmartForumContext();
// GET: ArgomentiPerAreas
public ActionResult Index()
var argomentiPerAreas = db.ArgomentiPerArea.Include(a => a.Area).Include(a => a.Moderatore);
string msg = "m";
return View(argomentiPerAreas.ToList());
.............
.............
I check in view and "moderatore" and "area" have null value.
I don't understand but I know database first and MVC superficially. I hope in some suggestions.
c# entity-framework ef-database-first
asp.net-mvc has nothing to do with Entity Framework.
– Erik Philips
Mar 7 at 19:42
data are returned to view
– surferNet
Mar 7 at 19:49
add a comment |
I am learning MVC and for do this I am developing a "smart forum". I have do a database but I have some problem with entities. I have do this command
"Scaffold-DbContext "Server=(localdb)mssqllocaldb;Database=SmartForum;Trusted_Connection=True; Microsoft.EntityFrameworkCore.SqlServer -OutputDir ModelsFromDb" ,
A code snippet:
modelBuilder.Entity<ArgomentiPerArea>(entity =>
entity.HasKey(e => e.ArgomentoId);
entity.Property(e => e.ArgomentoId).HasColumnName("argomentoId");
entity.Property(e => e.Archiviato).HasColumnName("archiviato");
entity.Property(e => e.AreaId).HasColumnName("areaId");
entity.Property(e => e.ModeratoreId).HasColumnName("moderatoreId");
entity.Property(e => e.NomeArgomento).HasColumnName("nome_argomento");
entity.Property(e => e.NumeroRigaPerArea).HasColumnName("numero_riga_per_area");
entity.Property(e => e.TestoPerArgomento).HasColumnName("testo_per_argomento");
entity.HasOne(d => d.Area)
.WithMany(p => p.ArgomentiPerArea)
.HasForeignKey(d => d.AreaId)
.HasConstraintName("FK_ArgomentiPerArea_Aree");
entity.HasOne(d => d.Moderatore)
.WithMany(p => p.ArgomentiPerArea)
.HasForeignKey(d => d.ModeratoreId)
.HasConstraintName("FK_ArgomentiPerArea_Moderatori");
);
a second snippet :
public partial class ArgomentiPerArea
public ArgomentiPerArea()
Thread = new HashSet<Thread>();
[Key]
public int ArgomentoId get; set;
public string NomeArgomento get; set;
public int? AreaId get; set;
public bool? Archiviato get; set;
public int? NumeroRigaPerArea get; set;
public string TestoPerArgomento get; set;
public int? ModeratoreId get; set;
public virtual Aree Area get; set;
public virtual Moderatori Moderatore get; set;
public virtual ICollection<Thread> Thread get; set;
public partial class Aree
public Aree()
ArgomentiPerArea = new HashSet<ArgomentiPerArea>();
[Key]
public int AreaId get; set;
public string NomeArea get; set;
public int? NumeroRiga get; set;
public int? NumeroColonna get; set;
public virtual ICollection<ArgomentiPerArea> ArgomentiPerArea get; set;
public partial class Moderatori
public Moderatori()
ArgomentiPerArea = new HashSet<ArgomentiPerArea>();
SegnalazioniPerModeratori = new HashSet<SegnalazioniPerModeratori>();
[Key]
public int ModeratoreId get; set;
public string UsernameModeratore get; set;
public string PasswordHash get; set;
public string NomeCognome get; set;
public bool? Archiviato get; set;
public virtual ICollection<ArgomentiPerArea> ArgomentiPerArea get; set;
public virtual ICollection<SegnalazioniPerModeratori> SegnalazioniPerModeratori get; set;
when this code run
public class ArgomentiPerAreasController : Controller
private ModelsFromDb.SmartForumContext db = new ModelsFromDb.SmartForumContext();
// GET: ArgomentiPerAreas
public ActionResult Index()
var argomentiPerAreas = db.ArgomentiPerArea.Include(a => a.Area).Include(a => a.Moderatore);
string msg = "m";
return View(argomentiPerAreas.ToList());
.............
.............
I check in view and "moderatore" and "area" have null value.
I don't understand but I know database first and MVC superficially. I hope in some suggestions.
c# entity-framework ef-database-first
I am learning MVC and for do this I am developing a "smart forum". I have do a database but I have some problem with entities. I have do this command
"Scaffold-DbContext "Server=(localdb)mssqllocaldb;Database=SmartForum;Trusted_Connection=True; Microsoft.EntityFrameworkCore.SqlServer -OutputDir ModelsFromDb" ,
A code snippet:
modelBuilder.Entity<ArgomentiPerArea>(entity =>
entity.HasKey(e => e.ArgomentoId);
entity.Property(e => e.ArgomentoId).HasColumnName("argomentoId");
entity.Property(e => e.Archiviato).HasColumnName("archiviato");
entity.Property(e => e.AreaId).HasColumnName("areaId");
entity.Property(e => e.ModeratoreId).HasColumnName("moderatoreId");
entity.Property(e => e.NomeArgomento).HasColumnName("nome_argomento");
entity.Property(e => e.NumeroRigaPerArea).HasColumnName("numero_riga_per_area");
entity.Property(e => e.TestoPerArgomento).HasColumnName("testo_per_argomento");
entity.HasOne(d => d.Area)
.WithMany(p => p.ArgomentiPerArea)
.HasForeignKey(d => d.AreaId)
.HasConstraintName("FK_ArgomentiPerArea_Aree");
entity.HasOne(d => d.Moderatore)
.WithMany(p => p.ArgomentiPerArea)
.HasForeignKey(d => d.ModeratoreId)
.HasConstraintName("FK_ArgomentiPerArea_Moderatori");
);
a second snippet :
public partial class ArgomentiPerArea
public ArgomentiPerArea()
Thread = new HashSet<Thread>();
[Key]
public int ArgomentoId get; set;
public string NomeArgomento get; set;
public int? AreaId get; set;
public bool? Archiviato get; set;
public int? NumeroRigaPerArea get; set;
public string TestoPerArgomento get; set;
public int? ModeratoreId get; set;
public virtual Aree Area get; set;
public virtual Moderatori Moderatore get; set;
public virtual ICollection<Thread> Thread get; set;
public partial class Aree
public Aree()
ArgomentiPerArea = new HashSet<ArgomentiPerArea>();
[Key]
public int AreaId get; set;
public string NomeArea get; set;
public int? NumeroRiga get; set;
public int? NumeroColonna get; set;
public virtual ICollection<ArgomentiPerArea> ArgomentiPerArea get; set;
public partial class Moderatori
public Moderatori()
ArgomentiPerArea = new HashSet<ArgomentiPerArea>();
SegnalazioniPerModeratori = new HashSet<SegnalazioniPerModeratori>();
[Key]
public int ModeratoreId get; set;
public string UsernameModeratore get; set;
public string PasswordHash get; set;
public string NomeCognome get; set;
public bool? Archiviato get; set;
public virtual ICollection<ArgomentiPerArea> ArgomentiPerArea get; set;
public virtual ICollection<SegnalazioniPerModeratori> SegnalazioniPerModeratori get; set;
when this code run
public class ArgomentiPerAreasController : Controller
private ModelsFromDb.SmartForumContext db = new ModelsFromDb.SmartForumContext();
// GET: ArgomentiPerAreas
public ActionResult Index()
var argomentiPerAreas = db.ArgomentiPerArea.Include(a => a.Area).Include(a => a.Moderatore);
string msg = "m";
return View(argomentiPerAreas.ToList());
.............
.............
I check in view and "moderatore" and "area" have null value.
I don't understand but I know database first and MVC superficially. I hope in some suggestions.
c# entity-framework ef-database-first
c# entity-framework ef-database-first
edited Mar 7 at 20:15
Brian Tompsett - 汤莱恩
4,2421339103
4,2421339103
asked Mar 7 at 19:41
surferNetsurferNet
141
141
asp.net-mvc has nothing to do with Entity Framework.
– Erik Philips
Mar 7 at 19:42
data are returned to view
– surferNet
Mar 7 at 19:49
add a comment |
asp.net-mvc has nothing to do with Entity Framework.
– Erik Philips
Mar 7 at 19:42
data are returned to view
– surferNet
Mar 7 at 19:49
asp.net-mvc has nothing to do with Entity Framework.
– Erik Philips
Mar 7 at 19:42
asp.net-mvc has nothing to do with Entity Framework.
– Erik Philips
Mar 7 at 19:42
data are returned to view
– surferNet
Mar 7 at 19:49
data are returned to view
– surferNet
Mar 7 at 19:49
add a comment |
1 Answer
1
active
oldest
votes
This is likely due to circular references between your Argomenti* & the Moderator/Area. An Area holds a collection back to the Argomenti* so when MVC goes to serialize the root entity (Argomenti) it comes across the Area, then iterating through the area, a collection of Argomenti*, and co the cycle goes. It bails out and doesn't attempt to serialize the cyclical dependencies.
Generally the best thing to do with EF and views is not to attempt to send entities to the view. Instead, create a POCO (Plain old C# object) View Model to send to the view. This view model contains only the fields needed by the view, and your EF query uses .Select()
to populate that view model. This avoids the whole cyclic reference issue, and negates the need for deliberate eager loading (.Include()
) or the performance risk of lazy loading.
For example: If I want a list of Argumenti, and I want to display each Area and Moderator as part of that:
[Serializable]
public class ArgumentiViewModel
public string NomeArgomento get; set;
public bool? Archiviato get; set;
public int? NumeroRigaPerArea get; set;
public string TestoPerArgomento get; set;
public string NomeArea get; set; // From Area
public string NomeCognome get; set; // From Moderator
Then when I want to return this to the view:
var argomentiViewModels = db.ArgomentiPerArea
.Select(x => new ArgomentiViewModel
NomeArgomento = x.NomeArgomento,
Archiviato - x.Archiviato,
NumeroRigaPerArea = x.NumeroRigaPerArea,
TestoPerArgomento = x.TestoPerArgomento,
NomeArea = x.Area.NomeArea, // From Area
NomeCognome = x.Moderatori.NomeCognome // From Moderator
).ToList();
string msg = "m";
return View(argomentiViewModels);
I sumarized a couple good reasons why code should not return Entities to the view here.
add a comment |
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55051635%2fproblem-using-related-entities-in-database-first%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
This is likely due to circular references between your Argomenti* & the Moderator/Area. An Area holds a collection back to the Argomenti* so when MVC goes to serialize the root entity (Argomenti) it comes across the Area, then iterating through the area, a collection of Argomenti*, and co the cycle goes. It bails out and doesn't attempt to serialize the cyclical dependencies.
Generally the best thing to do with EF and views is not to attempt to send entities to the view. Instead, create a POCO (Plain old C# object) View Model to send to the view. This view model contains only the fields needed by the view, and your EF query uses .Select()
to populate that view model. This avoids the whole cyclic reference issue, and negates the need for deliberate eager loading (.Include()
) or the performance risk of lazy loading.
For example: If I want a list of Argumenti, and I want to display each Area and Moderator as part of that:
[Serializable]
public class ArgumentiViewModel
public string NomeArgomento get; set;
public bool? Archiviato get; set;
public int? NumeroRigaPerArea get; set;
public string TestoPerArgomento get; set;
public string NomeArea get; set; // From Area
public string NomeCognome get; set; // From Moderator
Then when I want to return this to the view:
var argomentiViewModels = db.ArgomentiPerArea
.Select(x => new ArgomentiViewModel
NomeArgomento = x.NomeArgomento,
Archiviato - x.Archiviato,
NumeroRigaPerArea = x.NumeroRigaPerArea,
TestoPerArgomento = x.TestoPerArgomento,
NomeArea = x.Area.NomeArea, // From Area
NomeCognome = x.Moderatori.NomeCognome // From Moderator
).ToList();
string msg = "m";
return View(argomentiViewModels);
I sumarized a couple good reasons why code should not return Entities to the view here.
add a comment |
This is likely due to circular references between your Argomenti* & the Moderator/Area. An Area holds a collection back to the Argomenti* so when MVC goes to serialize the root entity (Argomenti) it comes across the Area, then iterating through the area, a collection of Argomenti*, and co the cycle goes. It bails out and doesn't attempt to serialize the cyclical dependencies.
Generally the best thing to do with EF and views is not to attempt to send entities to the view. Instead, create a POCO (Plain old C# object) View Model to send to the view. This view model contains only the fields needed by the view, and your EF query uses .Select()
to populate that view model. This avoids the whole cyclic reference issue, and negates the need for deliberate eager loading (.Include()
) or the performance risk of lazy loading.
For example: If I want a list of Argumenti, and I want to display each Area and Moderator as part of that:
[Serializable]
public class ArgumentiViewModel
public string NomeArgomento get; set;
public bool? Archiviato get; set;
public int? NumeroRigaPerArea get; set;
public string TestoPerArgomento get; set;
public string NomeArea get; set; // From Area
public string NomeCognome get; set; // From Moderator
Then when I want to return this to the view:
var argomentiViewModels = db.ArgomentiPerArea
.Select(x => new ArgomentiViewModel
NomeArgomento = x.NomeArgomento,
Archiviato - x.Archiviato,
NumeroRigaPerArea = x.NumeroRigaPerArea,
TestoPerArgomento = x.TestoPerArgomento,
NomeArea = x.Area.NomeArea, // From Area
NomeCognome = x.Moderatori.NomeCognome // From Moderator
).ToList();
string msg = "m";
return View(argomentiViewModels);
I sumarized a couple good reasons why code should not return Entities to the view here.
add a comment |
This is likely due to circular references between your Argomenti* & the Moderator/Area. An Area holds a collection back to the Argomenti* so when MVC goes to serialize the root entity (Argomenti) it comes across the Area, then iterating through the area, a collection of Argomenti*, and co the cycle goes. It bails out and doesn't attempt to serialize the cyclical dependencies.
Generally the best thing to do with EF and views is not to attempt to send entities to the view. Instead, create a POCO (Plain old C# object) View Model to send to the view. This view model contains only the fields needed by the view, and your EF query uses .Select()
to populate that view model. This avoids the whole cyclic reference issue, and negates the need for deliberate eager loading (.Include()
) or the performance risk of lazy loading.
For example: If I want a list of Argumenti, and I want to display each Area and Moderator as part of that:
[Serializable]
public class ArgumentiViewModel
public string NomeArgomento get; set;
public bool? Archiviato get; set;
public int? NumeroRigaPerArea get; set;
public string TestoPerArgomento get; set;
public string NomeArea get; set; // From Area
public string NomeCognome get; set; // From Moderator
Then when I want to return this to the view:
var argomentiViewModels = db.ArgomentiPerArea
.Select(x => new ArgomentiViewModel
NomeArgomento = x.NomeArgomento,
Archiviato - x.Archiviato,
NumeroRigaPerArea = x.NumeroRigaPerArea,
TestoPerArgomento = x.TestoPerArgomento,
NomeArea = x.Area.NomeArea, // From Area
NomeCognome = x.Moderatori.NomeCognome // From Moderator
).ToList();
string msg = "m";
return View(argomentiViewModels);
I sumarized a couple good reasons why code should not return Entities to the view here.
This is likely due to circular references between your Argomenti* & the Moderator/Area. An Area holds a collection back to the Argomenti* so when MVC goes to serialize the root entity (Argomenti) it comes across the Area, then iterating through the area, a collection of Argomenti*, and co the cycle goes. It bails out and doesn't attempt to serialize the cyclical dependencies.
Generally the best thing to do with EF and views is not to attempt to send entities to the view. Instead, create a POCO (Plain old C# object) View Model to send to the view. This view model contains only the fields needed by the view, and your EF query uses .Select()
to populate that view model. This avoids the whole cyclic reference issue, and negates the need for deliberate eager loading (.Include()
) or the performance risk of lazy loading.
For example: If I want a list of Argumenti, and I want to display each Area and Moderator as part of that:
[Serializable]
public class ArgumentiViewModel
public string NomeArgomento get; set;
public bool? Archiviato get; set;
public int? NumeroRigaPerArea get; set;
public string TestoPerArgomento get; set;
public string NomeArea get; set; // From Area
public string NomeCognome get; set; // From Moderator
Then when I want to return this to the view:
var argomentiViewModels = db.ArgomentiPerArea
.Select(x => new ArgomentiViewModel
NomeArgomento = x.NomeArgomento,
Archiviato - x.Archiviato,
NumeroRigaPerArea = x.NumeroRigaPerArea,
TestoPerArgomento = x.TestoPerArgomento,
NomeArea = x.Area.NomeArea, // From Area
NomeCognome = x.Moderatori.NomeCognome // From Moderator
).ToList();
string msg = "m";
return View(argomentiViewModels);
I sumarized a couple good reasons why code should not return Entities to the view here.
answered Mar 7 at 22:04
Steve PySteve Py
6,24311020
6,24311020
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55051635%2fproblem-using-related-entities-in-database-first%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
asp.net-mvc has nothing to do with Entity Framework.
– Erik Philips
Mar 7 at 19:42
data are returned to view
– surferNet
Mar 7 at 19:49