我如何可以将一个实体框架对象不是从数据库中?是从、数据库中、实体、框架

2023-09-07 01:59:43 作者:夏末

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

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

即:

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

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

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:

有一个空的EntityKey值的对象   不能被附加到对象   上下文。

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

编辑: 它看起来像我必须使用entities.AttachTo(作者,dbAuthor);附加没有的EntityKey,不过那时候我也很难$ C $光盘魔法字符串,这将打破,如果我改变我的实体集的名字都和我不会有任何编译时检查...有没有一种方法,我可以附加,保持编译时检查?

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?

我希望我能够做到这一点,因为硬codeD串杀死编译时验证回敬=)

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

推荐答案

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

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

entities.AttachTo("Authors", dbAuthor);

其中,作者将您的实际实体集的名字。

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

编辑: 是的,有一个更好的方法(也应该)。设计者应已生成添加方法的ObjectContext的为你而译出上面的电话。所以,你应该能够做到:

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);
}

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

defined in the whateverobjectcontext.designer.cs file.