开发者

MVC3 Object with a Collection of Child Objects

开发者 https://www.devze.com 2023-04-12 15:04 出处:网络
I have an MVC3 Project in C#.Net.开发者_如何转开发I have Object1 with a list of Object2... //navigation Property(s)

I have an MVC3 Project in C#.Net. 开发者_如何转开发I have Object1 with a list of Object2...

    //navigation Property(s)
    public virtual ICollection<Object2> Object2s { get; set; }

Object2 has an Object1 property and an Object1_Id property

    public int Object1_Id { get; set; }
    public virtual Object1 Object1 { get; set; }

When I run the Index View for Object2 I get the message "Invalid column name 'Object1_Id1'". Weird....it's looking for an automated column. When I remove the Object1_Id from Object2, it does fine until I go to Save in the Create View. It then throws an error message:

{"Cannot insert the value NULL into column 'Object1_Id', table 'dbo.Object2'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}

I'm sure I'm just missing an easy step. Any ideas?


You want to use fluent API to make the adjustment. You can do this in your DB Context class. Look toward the bottom of the page of this link to see a sample of using fluent API.

http://www.asp.net/entity-framework/tutorials/creating-a-more-complex-data-model-for-an-asp-net-mvc-application

    public class ObjectContext : DbContext
    {
        public DbSet<Object1> Object1s{ get; set; }
        public DbSet<Object2> Object2s{ get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Entity<Object2>()
                .HasOptional(o => o.Object1).WithRequired(o => o.Object2);
        }
    }


I figured out my question. When I call the Create post action on my Object2 Controller, I retrieve the parent Object1, create a Guid for my new Object2, add the new Object2 to the Object1.Object2s collection, set Object1 state to modified, then save the db:

            var object1ToUpdate = db.Object1s.Where(
                    aObject1 => aObject1.Id.Equals(myId)
                ).Include(aObject1 => aObject1.Object2s).Single();
            string id = Guid.NewGuid().ToString();
            Object2.Id = Guid.NewGuid();
            object1ToUpdate.Object2s.Add(Object2);
            db.Entry(object1ToUpdate).State = EntityState.Modified;
            db.SaveChanges();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号