标签: entity-framework-4

实体框架4 Code First和new()运算符

我有一个相当深的对象层次结构,我试图坚持使用Entity Framework 4,POCO,PI(Persistence Ignorance)和Code First.突然之间,当我突然意识到不使用new()运算符时,事情开始变得很好.最初编写时,对象经常使用new()来创建子对象.

相反,我正在使用我对存储库模式的看法来根据需要创建所有子对象.例如,给定:

class Adam
{
  List<Child> children;
  void AddChildGivenInput(string input) { children.Add(new Child(...)); }
}

class Child
{
  List<GrandChild> grandchildren;
  void AddGrandChildGivenInput(string input) { grandchildren.Add(new GrandChild(...)); }
}

class GrandChild
{
}
Run Code Online (Sandbox Code Playgroud)

("GivenInput"表示此处未显示的某些处理)

我定义了一个AdamRepository像:

class AdamRepository
{
    Adam Add() 
    { 
        return objectContext.Create<Adam>(); 
    }
    Child AddChildGivenInput(Adam adam, string input) 
    { 
        return adam.children.Add(new Child(...)); 
    }
    GrandChild AddGrandchildGivenInput(Child child, string input) 
    { 
        return child.grandchildren.Add(new GrandChild(...)); 
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,这很好用.但是,我不再"无知"我的持久性机制,因为我放弃了new()运算符.

此外,我有一个贫血领域模型的风险,因为这么多的逻辑最终存储在存储库而不是域对象中.

经过多次讨论,一个问题:

或者更确切地说......

  • 这种模式是否需要与EF 4 Code First一起使用? …

poco code-first entity-framework-4

6
推荐指数
1
解决办法
1854
查看次数

使用Entity Framework加入视图时使用.Include()

我使用索引视图,这是一个没有任何关系的实体(与我的表实体的关系将是更好的,但这似乎几乎不可能实现).这个视图由4个FK组成,它们共同构成了PK:

PortalID
CategoryID
BranchID
CompanyID
Run Code Online (Sandbox Code Playgroud)

现在我加入这个视图来选择这样一组公司:

var companies = (from c in database.Companies.FindAll().Include("City")
                 join l in database.CompanyList.FindAll() on c.ID equals l.CompanyID
                 where l.PortalID == 9 && l.BranchID == 1597
                 select c).Take(10);
Run Code Online (Sandbox Code Playgroud)

实体公司与表格(城市ID,城市)有关联,我想要包含并完美地运作.但是,当我加入视图时,.Include()被完全忽略,从而导致查询没有连接到cities表.

正如您可能已经使用存储库模式得出结论而FindAll()返回IQueryable并且我已经手动将Include扩展添加到IQueryable,如下所示:

public static IQueryable<T> Include<T>(this IQueryable<T> sequence, string path) {
    var objectQuery = sequence as ObjectQuery<T>;
    if (objectQuery != null)
        return objectQuery.Include(path);

    return sequence;
}
Run Code Online (Sandbox Code Playgroud)

我已经彻底测试了这个扩展,并且它应该像它一样工作

所以现在对于我的问题,为什么它忽略了最终表达式树中的Include操作,我怎么能阻止它这样做呢?

更新:
我从以下链接获得了我的解决方案:http: //blogs.msdn.com/b/alexj/archive/2009/06/02/tip-22-how-to-make-include-really-include.aspx

这说我需要像这样重写我的查询:

var companies = (from c in database.Companies.GetAll()
                 join l in database.CompanyList.GetAll() on c.ID equals l.CompanyID …
Run Code Online (Sandbox Code Playgroud)

c# sql entity-framework sql-server-2005 entity-framework-4

6
推荐指数
1
解决办法
9930
查看次数

使用C#与实体框架CTP 4的域建模问题

我正在尝试建立一个包含照片集的相册.每个专辑都有一组照片和一张拇指照片.这就是我所拥有的,但EF似乎并不喜欢它:

public class Album : IEntity {
        private DateTime _dateCreated;

        public Album() {
            _dateCreated = SystemTime.Now();
            Photos = new List<Photo>();
        }
        public long Id { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
        public DateTime DateCreated
        {
            get { return _dateCreated; }
            set { _dateCreated = value; }
        }
        public virtual Site Site { get; set; }
        public virtual Photo Thumbnail { get; set; }
        public virtual ICollection<Photo> Photos { get; …
Run Code Online (Sandbox Code Playgroud)

domain-driven-design entity-framework-4 ef-code-first

6
推荐指数
1
解决办法
657
查看次数

WCF数据服务(OData),具有继承限制的查询?

项目:使用内部EF4 CTP5代码优先方法的WCF数据服务.

我配置了具有继承(TPH)的实体.查看有关此主题的上一个问题:

以前关于多个实体的问题 - 同一个表

映射效果很好,EF4上的单元测试确认查询运行顺利.

我的实体看起来像这样:

  • ContactBase(摘要)
  • Customer(继承自ContactBase),此实体还具有针对其他实体的多个Navigation属性
  • 资源(继承自ContactBase)

我已配置了一个鉴别器,因此Customer和Resource都映射到同一个表.同样,在Ef4的观点上,每个事情都可以正常工作(单元测试所有绿色!)

但是,当通过WCF数据服务公开这个DBContext时,我得到: - CustomerBases设置暴露(客户和资源集似乎是隐藏的,是设计吗?) - 当我在客户上查询Odata时,我收到此错误:

Navigation Properties are not supported on derived entity types. Entity Set 'ContactBases' has a instance of type 'CodeFirstNamespace.Customer', which is an derived entity type and has navigation properties. Please remove all the navigation properties from type 'CodeFirstNamespace.Customer'. 
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪:

at System.Data.Services.Serializers.SyndicationSerializer.WriteObjectProperties(IExpandedResult expanded, Object customObject, ResourceType resourceType, Uri absoluteUri, String relativeUri, SyndicationItem item, DictionaryContent content, EpmSourcePathSegment currentSourceRoot)
at System.Data.Services.Serializers.SyndicationSerializer.WriteEntryElement(IExpandedResult expanded, Object element, ResourceType expectedType, Uri …
Run Code Online (Sandbox Code Playgroud)

inheritance entity-framework entity-framework-4 wcf-data-services odata

6
推荐指数
1
解决办法
2511
查看次数

使用SQL Server CE 4或SQLite与Entity Framework 4 Code First进行集成测试

我想从集成测试开始.我正在使用ASP.NET MVC 3应用程序.我正在使用Entity Framework 4 Code First CTP5.我对数据库的集成测试是在一个单独的项目中,类似于MyProject.Data.IntegrationTests.

我打算使用SQL Server CE 4或SQLite.有关使用其中任何一项的建议/提示/意见,我想要完成的任务?

有谁知道我能读到的关于我想要完成的任何体面的文章?并且将非常感谢帮助/反馈.

我正在使用SQL Server 2008作为我的数据库.但是在测试我的存储库时,我想针对上面提到的其中一个数据库测试它们,所以我需要指定连接字符串.

UPDATE

我从服务层(从我的控制器调用)工作,然后服务层将调用我的存储库.例如,下面是我如何添加新闻项:

服务类:

public class NewsService : INewsService
{
   private INewsRepository newsRepository;

   public NewsService(INewsRepository newsRepository)
   {
      this.newsRepository = newsRepository;
   }

   public News Insert(News news)
   {
      // Insert news item
      News newNews = newsRepository.Insert(news);

      // Insert audit entry

      // Return the inserted news item's unique identifier
      return newNews;
   }
}
Run Code Online (Sandbox Code Playgroud)

存储库类:

public class NewsRepository : INewsRepository
{
   MyContext context = new MyContext();

   public NewsRepository()
   { …
Run Code Online (Sandbox Code Playgroud)

sql-server sqlite entity-framework sql-server-ce entity-framework-4

6
推荐指数
1
解决办法
2192
查看次数

实体框架转换错误

以下工作完美:

IQueryable<Property> PropertyQuery = PropertyDAO.SearchWithAdditionalParameters(/* elided */);
IQueryable<long> propertyIdQuery = PropertyQuery.Select(p => p.PropertyId);

var relevantFMVs = PropertyDAO.db.FMVHistories.Where(f => propertyIdQuery.Contains(f.PropertyId)).ToList();
Run Code Online (Sandbox Code Playgroud)

但是以下情况爆发了:

IQueryable<Property> PropertyQuery = PropertyDAO.SearchWithAdditionalParameters(/* elided */);

var relevantFMVs = PropertyDAO.db.FMVHistories.Where(f => PropertyQuery.Select(p => p.PropertyId).Contains(f.PropertyId)).ToList();
Run Code Online (Sandbox Code Playgroud)

(请注意,我没有单独创建propertyIdQuery,而只是将变量本身替换为查询本身)

例外是

无法转换类型'System.Linq.IQueryable 1' to type 'System.Linq.IQueryable1'.LINQ to Entities仅支持转换实体数据模型基元类型.

有人可以了解EF(4)在封面下做什么只做第一次查询工作,即使它们表面上是等效的吗?

我知道IQueryable<T>,表达树在幕后做了很多事情,但是如何将中间步骤保存到局部变量会影响结果呢?

编辑

根据请求,这是被调用的完整方法,以及该方法调用的方法:

    public IQueryable<Property> BasicSearchFromConstraints(PropertyInvoiceConstraints constraints) {
        return ExecuteSearchFromConstraints((dynamic)constraints.PropertyInst, constraints.CompanyNumber, constraints.TaxSubType, constraints.PhaseID, constraints.State, constraints.County, constraints.City, constraints.Jurisdiction);
    }

    private IQueryable<T> ExecuteSearchFromConstraints<T>(T property, int CompanyNumber, byte SubType, byte PhaseID, string State, string County, string …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework iqueryable entity-framework-4

6
推荐指数
1
解决办法
1816
查看次数

实体框架 - 在结束使用后保持加载/包含的相关对象?

我试图在一个看起来像这样的方法中查询:

Public Shared Function listParticipationsByTeamCount(ByVal count As Integer, ByVal challenge As Challenge) As List(Of Participation)
    Dim participationList As List(Of Participation)

    If count <> Nothing And challenge IsNot Nothing Then
        Using db As New DatabaseEntities()
            participationList = db.Participations.Where(Function(x) x.TeamCount = count And x.Challenge.Id = challenge.Id).OrderByDescending(Function(x) x.TeamCount).ThenBy(Function(x) x.Team.Name).ToList()
        End Using
    End If

    Return participationList
End Function
Run Code Online (Sandbox Code Playgroud)

我有一个Participation表,它在Participation和Team表之间有多对一的关系,并且Participation和TeamMember表之间有多对多的关系.在我的标记页面上,当我迭代遍历列表时,我会尝试这样的事情:

<% For Each participation As Participation In participationsList%>
    <tr>
        <td><a class="external-link" href="<%= participation.Team.Website %>"><%= participation.Team.Name%></a></td> …
Run Code Online (Sandbox Code Playgroud)

.net entity-relationship entity-framework entity-framework-4

6
推荐指数
1
解决办法
438
查看次数

EF4和AddObject对相关集合的意外加载

我有一个奇怪的情况,添加一个记录导致不必要的相关集合加载.

例如,我有请求和会话.会话可以包含许多请求.我已经加载了会话,只想添加一个新请求.

但是,当我在请求存储库的ObjectSet上设置调用AddObject时,SQL事件探查器会显示对该会话上的所有相关请求执行的选择查询.

这是问题代码:

this._request = new Request
                    {
                        Action = (string)filterContext.RouteData.Values["action"],
                        Controller = filterContext.Controller.GetType().Name,
                        DateAdded = userContext.Session.DateLastActive,
                        IpAddress = filterContext.HttpContext.Request.UserHostAddress,
                        SessionId = userContext.Session.Id
                    };

loggingService.AddRequest(this._request);
Run Code Online (Sandbox Code Playgroud)

最后一行只调用我的服务,而这只是调用_objectSet.AddObject(entity).

如果我尝试设置新的Request Session = userContext.Session(而不是上面的SessionId = userContext.Session.Id),也会发生同样的事情- 查询将在设置此属性时执行,而不是在AddObject上执行.所以看来EF4认为它需要会话的相关Request集合,因为它被引用的原因.

但我不需要会话上的相关请求,也不需要使用或引用.所以我不确定为什么EF4会加载它们.我逐步完成了代码,并验证了这种情况正好AddObject(entity)在线上(Profiler显示查询在同一个实例中执行).

为什么会发生这种情况,我怎么能阻止它呢?

提前致谢.

编辑:这是因为EF4正在尝试将新请求添加到相关的Session.Requests集合中,并检索所有其他的请求吗?如果是这样,有什么办法可以阻止这种情况吗?就像我说的,我不需要那些请求,我只需要添加它并继续前进.

entity-framework lazy-loading eager-loading entity-framework-4

6
推荐指数
1
解决办法
1265
查看次数

实体框架 - 在sql server表中未设置默认值

SQL Server 2005数据库表有一个'createdon'列,其默认值设置为getdate().我正在尝试使用实体框架添加记录.'createdon'列未获得更新.

我是否错过了Entity框架中的任何属性,请提出建议.

c# sql-server-2005 entity-framework-4

6
推荐指数
4
解决办法
1万
查看次数

由于EF代码迁移,Teamcity构建失败

我的TeamCity构建失败,因为我有一个项目,其中包含2个EF代码迁移配置.

从构建日志:

[12:39:58]Checking for changes
[12:39:58]Collecting changes in 1 VCS root (1s)
[12:40:00]Clearing temporary directory: C:\TeamCity\buildAgent2\temp\buildTmp
[12:40:00]Publishing internal artifacts
[12:40:00]Checkout directory: C:\TeamCity\buildAgent2\work\1679b8b30e00ad0
[12:40:00]Updating sources: server side checkout (2s)
[12:40:03]Step 1/8: Gulp (Command Line)
[12:40:03]Step 2/8: Nuget Package Refresh (NuGet Installer) (3s)
[12:40:06]Step 3/8: Compile (MSBuild) (21s)
[12:40:27]Step 4/8: Unit Tests (NUnit) (33s)
[12:41:01]Step 5/8: Transform Files (Powershell) (2s)
[12:41:03]Step 6/8: Deployment Build on XXXXX Live (MSBuild) (25s)
[12:41:29]Step 7/8: Deploy Database (Powershell) (5s)
[12:41:34]Step 8/8: Deploy Portal.Hub (Powershell) (33s)
[12:42:08]Publishing …
Run Code Online (Sandbox Code Playgroud)

teamcity entity-framework-4 ef-migrations teamcity-8.0

6
推荐指数
1
解决办法
843
查看次数