如何附加不是从数据库中的Entity Framework对象? [英] How can I attach an Entity Framework object that isn't from the database?

查看:109
本文介绍了如何附加不是从数据库中的Entity Framework对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全分离了我的实体框架对象和我的POCO对象,我只是来回翻译它们。



ie:

  // poco 
public class作者
{
public Guid Id {get;组; }
public string UserName {get;组; }
}

然后我有一个具有相同属性的EF对象Authors。



所以我有我的业务对象

  var author = new作者{UserName =foo,Id =Guid thats in the db}; 

我想保存此对象,以便执行以下操作:

  var dbAuthor = new dbAuthor {Id = author.Id,UserName = author.UserName}; 
entities.Attach(dbAuthor);
entities.SaveChanges();

但这会给我以下错误:



< blockquote>

具有null EntityKey值
的对象不能附加到对象
上下文。


编辑:
看起来我必须使用entities.AttachTo(Authors,dbAuthor);附加没有EntityKey,但是我有硬编码的魔术字符串,如果我更改我的实体集名称,我将不会有任何编译时检查...有没有办法我可以附加的编译时间检查?我希望我能够做到这一点,因为硬编码的字符串会导致编译时间的验证会被吸收。)

解决方案

您是否尝试使用 AttachTo 并指定实体集?..

  entities.AttachTo (作者,dbAuthor); 

其中作者将是您的实际实体集名称。



编辑:

是否有更好的方法(应该有)。设计人员应该生成添加方法到您的ObjectContext,转换到上面的调用。所以你应该可以做到:

 实体.AddToAuthors(dbAuthor); 

这应该是:

  public void AddToAuthors(作者作者)
{
base.AddObject(Authors,authors);
}

在whateverobjectcontext.designer.cs文件中定义。


I have a complete separation of my Entity Framework objects and my POCO objects, I just translate them back and forth...

i.e:

// poco
public class Author
{
   public Guid Id { get; set; }
   public string UserName { get; set; }
}

and then I have an EF object "Authors" with the same properties..

So I have my business object

var author = new Author { UserName="foo", Id="Guid thats in the db" };

and I want to save this object so I do the following:

var dbAuthor = new dbAuthor { Id=author.Id, UserName=author.UserName };
entities.Attach(dbAuthor);
entities.SaveChanges();

but this gives me the following error:

An object with a null EntityKey value cannot be attached to an object context.

EDIT: It looks like I have to use entities.AttachTo("Authors", dbAuthor); to attach without an EntityKey, but then I have hard coded magic strings, which will break if I change my entity set names at all and I wont have any compile time checking... Is there a way I can attach that keeps compile time checking?

I would hope I'd be able to do this, as hard coded strings killing off compile time validation would suck =)

解决方案

Have you tried using AttachTo and specifying the entity set?..

entities.AttachTo("Authors", dbAuthor);

where "Authors" would be your actual entity set name.

Edit:
Yes there is a better way (well there should be). The designer should have generated "Add" methods to the ObjectContext for you which translate out to the call above.. So you should be able to do:

entities.AddToAuthors(dbAuthor);

which should literally be:

public void AddToAuthors(Authors authors)
{
    base.AddObject("Authors", authors);
}

defined in the whateverobjectcontext.designer.cs file.

这篇关于如何附加不是从数据库中的Entity Framework对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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