简体   繁体   English

EntityFramework 如何按日期时间删除行

[英]EntityFramework How Can I Delete Lines by DateTime

I use layered architecture.我使用分层架构。 I just started the Entity Framework.我刚刚启动了实体框架。 How can I delete lines by DateTime?如何按日期时间删除行? I share the entities layer and dataAccess layer.我共享实体层和数据访问层。

namespace Entities
{
    [Table("studentdetails")]
    public class GemkayDB : IEntity
    {
        [Key]
        public int ID { get; set; }
        public DateTime Time { get; set; }
        public string Type { get; set; }
        public string Name { get; set; }
        public string Explanation { get; set; }
    }
}

I want to delete according to DateTime.我想根据DateTime删除。

public void Sil(GemkayDB gemkayDB)
{
    using (var baglanti = new GemkayDBContext())
    {
        var eklenenEntity = baglanti.Entry(gemkayDB);
        eklenenEntity.State = EntityState.Deleted;
        baglanti.SaveChanges();
    }
}        

For example Time <= Now.Months('-2') .例如Time <= Now.Months('-2')

How can I do that?我怎样才能做到这一点?

The code you have written deleted items by primary key - you create some local entity that matches a DB entity and attach it to the local tracker, so effectively EF thinks it has downloaded it, then you set its state to deleted so that EF will think it has to issue a DELETE command to bring the entity in the db in sync with the local.您通过主键编写已删除项目的代码 - 您创建一些与数据库实体匹配的本地实体并将其附加到本地跟踪器,因此 EF 认为它已经下载了它,然后您将其 state 设置为删除,以便 EF 认为它必须发出 DELETE 命令以使数据库中的实体与本地同步。 This avoids downlaoding data from the DB, and just straight issues a delete for that entity with that primary key这避免了从数据库中下载数据,而只是直接使用该主键为该实体发出删除

If you want to delete entities in the same way based on some other field then you 'll have to create all the entities that would be affected, so they too can be deleted by their PK.如果您想基于其他字段以相同的方式删除实体,那么您必须创建所有将受到影响的实体,因此它们也可以通过其 PK 删除。 If you don't know which entities you want to delete, you'll either have to query them from the DB (ie download the entities with the relevant datetimes, so that EF knows which to delete; yourContext.SomeEntities.RemoveRange(yourContext.SomeEntities.Where(x => x.Time < DateTime.Now.AddMonths(-2)) ), or you'll have to issue a raw sql that perfroms the delete server side, based on the time as a WHERE predicate (eg dbContext.Database.ExecuteSqlCommand("DELETE FROM studentdetails WHERE Time < DATE_ADD(month, -2, GetUtcDate())") )如果您不知道要删除哪些实体,则必须从数据库中查询它们(即下载具有相关日期时间的实体,以便 EF 知道要删除哪些实体; yourContext.SomeEntities.RemoveRange(yourContext.SomeEntities.Where(x => x.Time < DateTime.Now.AddMonths(-2)) ),否则您将不得不发出一个原始 sql 执行删除服务器端,基于时间作为WHERE谓词(例如dbContext.Database.ExecuteSqlCommand("DELETE FROM studentdetails WHERE Time < DATE_ADD(month, -2, GetUtcDate())") )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM