CodeFirst.ApplyChanges? [英] CodeFirst.ApplyChanges?

查看:94
本文介绍了CodeFirst.ApplyChanges?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

对于使用CodeFirst的实体,ApplyChanges的优先/最佳实践方法是什么? 我想轻松地将它添加到我的DbContext中,而不必检查它是否存在。 使用SelfTrackingEntities,有一个简单的扩展方法(ApplyChanges)
,这使得这非常直接。 目前,似乎我必须做一些检查,看看实体是否存在于DbContext中,我想要解决这个问题。 :)

What is the preffered/best practice way to ApplyChanges to an entity with CodeFirst?  I want to easily add it to my DbContext without having to check to see if it exists.  With SelfTrackingEntities, there was a simple extension method (ApplyChanges) that made this very straight forward.  Currently, it appears that I have to do some checking to see if the entity exists within the DbContext and I'm wanting to get around that. :)

谢谢!

Michael

推荐答案

我很接近,但是CTP5中似乎有一个错误:

I am close on this, but there appears to be a bug in CTP5:

考虑以下扩展方法:


public static TEntity ApplyChanges<TEntity>( this DbContext target, TEntity entity ) where TEntity : class
{
	var set = target.Set<TEntity>();
	var values = target.ResolveKeyValues( entity );
	var current = set.Find( values );
	if ( current != null )
	{
		Update( target, entity, current );
	}
	else
	{
		target.Add( entity );
	}
	
	return entity;
}


这篇关于CodeFirst.ApplyChanges?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆