Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use List<model> by reference not by value?
    primarykey
    data
    text
    <p>OK. I have State which has List. I want to have multiple instances of State that use the same list of Series. </p> <pre><code>public class State { public int Id { get; set; } public string Name { get; set; } public virtual ICollection&lt;Series&gt; Serieses { get; set; } } public class Series { public int Id { get; set; } public string Name { get; set; } } </code></pre> <p>After Creating a State by typing in the Name of the State and selecting 1 or more Series from a ListBox: </p> <pre><code>public ActionResult Create(State state, FormCollection form) { // method to get selected Series from db foreach (var sItem in seriesModel//List of Possible Series) { foreach (var item in Selections//User selected Series) { if (sItem.Name == item.Name) { newSeries.Add(sItem); } } } state.Serieses = newSeries; _db.Entry(state).State = EntityState.Modified; _db.SaveChanges(); </code></pre> <p>The problem is after I create one instance of State with List. If I create a second instance and use the same Series in its list, the first will lose that Series in its list. So obviously Series is being passed by value and not reference. I'm new to C#, but back in C++ we would use pointers. That way if I change the original values of Series it will show up on each State list that points to it. I've also noticed in the Table Data in the Database, it has added a Foreign Key State_Id to every Series. Here's the Table Definition it created when I used Code First method.</p> <pre><code>CREATE TABLE [dbo].[Series] ( [Id] INT IDENTITY (1, 1) NOT NULL, [Name] NVARCHAR (MAX) NULL, [State_Id] INT NULL, CONSTRAINT [PK_dbo.Series] PRIMARY KEY CLUSTERED ([Id] ASC), CONSTRAINT [FK_dbo.Series_dbo.States_State_Id] FOREIGN KEY ([State_Id]) REFERENCES [dbo].[States] ([Id]) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload