var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);
string.Join(",",objectStateEntry.EntityKey.EntityKeyValues.Select(item=>item.Value.ToString()).ToArray());
此代码通过ef 6.0获取主键, 但是这个表有三个主键,当我运行这个代码时,关于EntityKeyValues的值为null,我不知道为什么它是null,我怎么得到主值?
答案 0 :(得分:1)
我知道为什么它会变为null,因为我添加了一条新记录,我没有保存到数据库,因此它无法获得任何值,谢谢大家。
答案 1 :(得分:0)
此灵魂使用MetadataWorkspace从任何实体检索所有主键名称。你可以修改它,以便适合你的灵魂。
域实体必须具有namepsace,否则您将获得null引用异常!。
namespace EntityFrameworkDemo
{
public class User
{
[Key, Column(Order = 0)]
public long Id { get; set; }
[Key, Column(Order = 1)]
public long SecondId { get; set; }
public bool Checked { get; set; }
}
}
public class Program
{
public class MyDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public MyDbContext(string connectionString)
: base("name=" + connectionString)
{
}
}
public static IEnumerable<string> GetEntityKeys(DbContext dbContext, Type type)
{
var keys = new Collection<string>();
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
var edmMembers = objectContext.MetadataWorkspace
.GetType(type.Name, type.Namespace, DataSpace.CSpace)
.MetadataProperties
.Where(mp => mp.Name == "KeyMembers")
.Select(x => x.Value)
.Cast<ReadOnlyCollection<EdmMember>>();
foreach (var key in edmMembers)
{
foreach (var edmMember in key)
{
keys.Add(edmMember.Name);
}
}
return keys;
}
public static void Main(string[] args)
{
Database.SetInitializer(new DropCreateDatabaseAlways<MyDbContext>());
using (var myDbContext = new MyDbContext("DatabaseConnectionString1"))
{
myDbContext.Users.Add(new User());
myDbContext.SaveChanges();
var user = myDbContext.Users.First();
var keys = GetEntityKeys(myDbContext, user.GetType());
foreach (var key in keys)
{
Console.WriteLine(key);
}
}
}
}
输出:
Id
SecondId