问题描述:

  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 want to pull all a object, but I can't find a way do do it.

  2. I want to do the lambada and the linq without return something but linq is always return something

    public static void addFavorits(long f,long idUser)

    {

    using (var db = dataBase())

    {

    // here i pull object user from users table

    var a = db.users.Where(c => c.id == idUser).SingleOrDefault();

    // here i adding to the object field myFavorits new value

    //myFavorits is also a table of entitys that connected to user object

    a.myFavorits.Add(new BE.FavoritsUsersLong { myLong = f });

    db.SaveChanges();

    }

    }

I thought to do something like this but i dont know how to set the field users_TableId that is the key that connect the 2 tables

public static void addFavorits(long favoritId,long idUser)

{

using (var db = dataBase())

{

db.favoritsUsersLong.Add(new BE.FavoritsUsersLong {myLong = favoritId}

/*,users_TableId =idUser*/);

db.SaveChanges();

}

}

网友答案:

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.
网友答案:

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(); 
}
相关阅读:
Top