How can I edit or add to a particular field without pull the all object

后端 未结 2 1978
Happy的楠姐
Happy的楠姐 2021-01-26 10:45
  1. How I can do just this ( a.myFavorits.Add()) without pulling the all object to var a , because a has a lot of data, and I don\'t

相关标签:
2条回答
  • 2021-01-26 10:52

    I'm guessing this is what you want? I don't see you 'editting' I only see you adding.

    using (var db = dataBase())
    {
        var a = new user(); 
         .... 
         //set properties etc..
         ...
        a.myFavorits.Add(new BE.FavoritsUsersLong { myLong = f });
        db.users.Add(a);
        db.SaveChanges(); 
    }
    
    0 讨论(0)
  • 2021-01-26 11:03

    Here's a concrete example that does what you want. In this example, only the Name of a Company is modified and saved. Or an item is added to one of its collections.

    var cmp = new Company{ CmpId = 1, Name = "Cmp1" }; // CmpId is the primary key
    db.Companies.Attach(cmp);
    db.Entry(cmp).Property(c => c.Name).IsModified = true;
    
    // Or add an entity to a collection:
    cmp.Users = new[] {new User { Name = "a1", PassWord = "a1" } };
    
    try
    {
        db.Configuration.ValidateOnSaveEnabled = false;
        db.SaveChanges();
    }
    finally
    {
        db.Configuration.ValidateOnSaveEnabled = true;
    }
    

    Result in SQL:

    DECLARE @0 VarChar(30) = 'Cmp1'
    DECLARE @1 Int = 1
    UPDATE [dbo].[Company]
    SET [Name] = @0
    WHERE ([CmpId] = @1)
    

    There are a few things to note here:

    • Obviously you need to know the Id of the entity you want to modify.
    • The object you create is called a stub entity, which is an incomplete entity. When you try to save such an entity, EF is very likely to complain about null values in required properties. That's why almost certain you'd have to disable validation (temporarily, or, better, dispose the context immediately).
    • If you want to add an item to a collection, you should leave validation enabled, because you'd want to know for sure that the new entity is valid. So you shouldn't mix these two ways to use a stub entity.
    • If you often need roughly the same small part of your entity you may consider table splitting.
    0 讨论(0)
提交回复
热议问题