实体框架代码第一个只读实体 [英] Entity Framework Code First ReadOnly Entity

查看:118
本文介绍了实体框架代码第一个只读实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解决方案

有没有办法将实体标记为只读,不指定任何密钥?您可以在Code First中执行只读的几件事情。第一个是在查询时使用 AsNoTracking()

  var readOnlyPeople =(from p in context.People 
其中p.LastName ==Smith
select p).AsNoTracking();

这告诉Code First不追踪这些实体的更改,因此当您调用 SaveChanges()不会对这些对象进行任何更改。



您可以做的第二件事情是将状态设置为不变之前调用 SaveChanges()

  context.Entry(person).State = EntityState.Unchanged; 
context.SaveChanges();

这告诉Code First忽略对该实体所做的任何更改。



只要没有密钥,所有实体都必须有一个密钥。这可能不一定映射到数据库中的主键,但它必须唯一标识实体集中的实体类型实例。


Is there any way to mark an entity as read-only and not specify any key for it?

解决方案

There are a couple of things that you can do to enforce read-only in Code First. The first is to use AsNoTracking() when you query.

var readOnlyPeople = (from p in context.People
                        where p.LastName == "Smith"
                        select p).AsNoTracking();

This tells Code First to not track changes to these entities, so when you call SaveChanges() no changes made to these objects will be persisted.

The seccond thing you can do is set the state to Unchanged before calling SaveChanges().

context.Entry(person).State = EntityState.Unchanged;
context.SaveChanges();

This tells Code First to ignore any changes that have been made to that entity.

As far as not having a key, all entities must have a key. This may not necessarily map to a primary key in the database, but it "must uniquely identify an entity type instance within an entity set".

这篇关于实体框架代码第一个只读实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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