Raven DB There is no reduce index named: 97 - ravendb
I have a problem with a Raven db index that suddenly stopped working properly.
public class GetStockListForCustomerIndex : AbstractIndexCreationTask<CustomerStock, GetStockListForCustomerIndex.Result>
{
public GetStockListForCustomerIndex()
{
this.Map = docs => from d in docs
from i in d.Items
select new Result
{
Id = i.Id,
Country = d.Country,
CustomerNumber = d.CustomerNumber,
Type = d.Type,
ItemNumber = i.ItemNumber,
ItemName = i.ItemName,
ItemNameSortingField = i.ItemName,
UnitCost = i.UnitCost,
Quantity = i.Quantity,
ReservationDate = i.ReservationStartDate,
Threshold = i.Threshold,
AvailableQuantity = i.Available,
QuantityLeft = i.QuantityLeft,
Reserved = i.Reserved,
AlwaysOne = 1,
Currency = i.Currency
};
this.Index(x => x.ItemNumber, FieldIndexing.Analyzed);
this.Index(x => x.ItemName, FieldIndexing.Analyzed);
this.Store(x => x.Id, FieldStorage.Yes);
this.Store(x => x.Country, FieldStorage.Yes);
this.Store(x => x.CustomerNumber, FieldStorage.Yes);
this.Store(x => x.Type, FieldStorage.Yes);
this.Store(x => x.ItemNumber, FieldStorage.Yes);
this.Store(x => x.ItemName, FieldStorage.Yes);
this.Store(x => x.ItemNameSortingField, FieldStorage.Yes);
this.Store(x => x.UnitCost, FieldStorage.Yes);
this.Store(x => x.Quantity, FieldStorage.Yes);
this.Store(x => x.ReservationDate, FieldStorage.Yes);
this.Store(x => x.Threshold, FieldStorage.Yes);
this.Store(x => x.AvailableQuantity, FieldStorage.Yes);
this.Store(x => x.QuantityLeft, FieldStorage.Yes);
this.Store(x => x.Reserved, FieldStorage.Yes);
this.Store(x => x.Currency, FieldStorage.Yes);
}
public class Result
{
public int Id { get; set; }
public string Country { get; set; }
public string CustomerNumber { get; set; }
public string Type { get; set; }
public string ItemNumber { get; set; }
public string ItemName { get; set; }
public string ItemNameSortingField { get; set; }
public Threshold Threshold { get; set; }
public int Quantity { get; set; }
public int? AvailableQuantity { get; set; }
public int? QuantityLeft { get; set; }
public int? Reserved { get; set; }
public decimal UnitCost { get; set; }
public DateTime ReservationDate { get; set; }
public int AlwaysOne { get; set; }
public string Currency { get; set; }
}
}
The query:
var result = this.Query
.ProjectFromIndexFieldsInto<GetStockListForCustomerIndex.Result>()
.Skip(this.PageSize * (this.Page - 1))
.Take(this.PageSize)
.OrderByDescending(x => x.ReservationDate)
.ToList();
Gives wrong result with duplicates items every time the database is updated. I tried:
this.store.DatabaseCommands.ResetIndex("GetStockListForCustomerIndex");
When updating the data. That solved the problem but only temporary, now the index does not contain any data at all.
I get the following error logs
Message
Failed to execute indexing
Exception
Raven.Abstractions.Exceptions.IndexDoesNotExistsException: There is no reduce index named: 97
at Raven.Database.Storage.Esent.StorageActions.DocumentStorageActions.TouchIndexEtag(Int32 id)
at Raven.Storage.Esent.TransactionalStorage.Batch(Action`1 action)
at Raven.Database.Tasks.RemoveFromIndexTask.Execute(WorkContext context)
at Raven.Database.Indexing.IndexingExecuter.<>c__DisplayClass6.<ExecuteTask>b__5(IStorageActionsAccessor actions)
at Raven.Storage.Esent.TransactionalStorage.Batch(Action`1 action)
at Raven.Database.Indexing.IndexingExecuter.ExecuteTask(HashSet`1 indexIds, Reference`1 foundWorkLocal)
at Raven.Database.Indexing.IndexingExecuter.<>c__DisplayClass2.<ExecuteTasksInternal>b__0(IStorageActionsAccessor actions)
at Raven.Storage.Esent.TransactionalStorage.ExecuteBatch(Action`1 action, EsentTransactionContext transactionContext)
at Raven.Storage.Esent.TransactionalStorage.Batch(Action`1 action)
at Raven.Database.Indexing.IndexingExecuter.ExecuteTasksInternal()
at Raven.Database.Indexing.IndexingExecuter.ExecuteTasks()
at Raven.Database.Indexing.AbstractIndexingExecuter.Execute()
Logged
a few seconds ago (12/15/17, 10:27am)
Level
Error
Logger
Raven.Database.Indexing.IndexingExecuter
And
Task for index: 97 (id: 97) has failed, details: Index: 97, Keys: customerstocks/8889089, customerstocks/8889090, customerstocks/8889091, customerstocks/8889092, customerstocks/8889093, customerstocks/8889094, customerstocks/8889095, customerstocks/8889096, customerstocks/8889097, customerstocks/8889098, customerstocks/8889099, customerstocks/8889100, customerstocks/8889101, customerstocks/8889102, customerstocks/8889103, customerstocks/8889104, customerstocks/8889105, customerstocks/8889106, customerstocks/8889107, customerstocks/8889108, customerstocks/8889109, customerstocks/8889110, customerstocks/8889111, customerstocks/8889112, customerstocks/8889113, customerstocks/8889114, customerstocks/8889115, customerstocks/8889116, customerstocks/8889117, customerstocks/8889118, customerstocks/8889119, customerstocks/8889120, customerstocks/8889121, customerstocks/8889122, customerstocks/8889123, customerstocks/8889124, customerstocks/8889125, customerstocks/8889126, customerstocks/8889127, customerstocks/8889128, customerstocks/8889129, customerstocks/8889130, customerstocks/8889131, customerstocks/8889132, customerstocks/8889133, customerstocks/8889134, customerstocks/8889135, customerstocks/8889136, customerstocks/8889137, customerstocks/8889138, customerstocks/8889139, customerstocks/8889140, customerstocks/8889141, customerstocks/8889142, customerstocks/8889143, customerstocks/8889144, customerstocks/8889145, customerstocks/8889146, customerstocks/8889147, customerstocks/8889148, customerstocks/8889149, customerstocks/8889150, customerstocks/8889151, customerstocks/8889152, customerstocks/8889153, customerstocks/8889154, customerstocks/8889155, customerstocks/8889156, customerstocks/8889157, customerstocks/8889158, customerstocks/8889159, customerstocks/8889160, customerstocks/8889161, customerstocks/8889162, customerstocks/8889163, customerstocks/8889164, customerstocks/8889165, customerstocks/8889166, customerstocks/8889167, customerstocks/8889168, customerstocks/8889169, customerstocks/8889170, customerstocks/8889171, customerstocks/8889172, customerstocks/8889173, customerstocks/8889174, customerstocks/8889175, customerstocks/8889176, customerstocks/8889177, customerstocks/8889178, customerstocks/8889179, customerstocks/8889180, customerstocks/8889181, customerstocks/8889182, customerstocks/8889183, customerstocks/8889184, customerstocks/8889185, customerstocks/8889186, customerstocks/8889187, customerstocks/8889188, customerstocks/8889189, customerstocks/8889190, customerstocks/8889191, customerstocks/8889192, customerstocks/8889193, customerstocks/8889194, customerstocks/8889195, customerstocks/8889196, customerstocks/8889197, customerstocks/8889198, customerstocks/8889199, customerstocks/8889200, customerstocks/8889201, customerstocks/8889202, customerstocks/8889203, customerstocks/8889204, customerstocks/8889205, customerstocks/8889206, customerstocks/8889207, customerstocks/8889208, customerstocks/8889209, customerstocks/8889210, customerstocks/8889211, customerstocks/8889212, customerstocks/8889213, customerstocks/8889214, customerstocks/8889215, customerstocks/8889216, customerstocks/8889217, customerstocks/8889218, customerstocks/8889219, customerstocks/8889220, customerstocks/8889221, customerstocks/8889222, customerstocks/8889223, customerstocks/8889224, customerstocks/8889225, customerstocks/8889226, customerstocks/8889227, customerstocks/8889228, customerstocks/8889229, customerstocks/8889230, customerstocks/8889231, customerstocks/8889232, customerstocks/8889233, customerstocks/8889234, customerstocks/8889235, customerstocks/8889236, customerstocks/8889237, customerstocks/8889238, customerstocks/8889239, customerstocks/8889240, customerstocks/8889241, customerstocks/8889242, customerstocks/8889243, customerstocks/8889244, customerstocks/8889245, customerstocks/8889246, customerstocks/8889247, customerstocks/8889248, customerstocks/8889249, customerstocks/8889250, customerstocks/8889251, customerstocks/8889252, customerstocks/8889253, customerstocks/8889254, customerstocks/8889255, customerstocks/8889256, customerstocks/8889257, customerstocks/8889258, customerstocks/8889259, customerstocks/8889260, customerstocks/8889261, customerstocks/8889262, customerstocks/8889263, customerstocks/8889264, customerstocks/8889265, customerstocks/8889266, customerstocks/8889267, customerstocks/8889268, customerstocks/8889269, customerstocks/8889270, customerstocks/8889271, customerstocks/8889272, customerstocks/8889273, customerstocks/8889274, customerstocks/8889275, customerstocks/8889276, customerstocks/8889277, customerstocks/8889278, customerstocks/8889279, customerstocks/8889280, customerstocks/8889281, customerstocks/8889282, customerstocks/8889283, customerstocks/8889284, customerstocks/8889285, customerstocks/8889286, customerstocks/8889287, customerstocks/8889288, customerstocks/8889289, customerstocks/8889290, customerstocks/8889291, customerstocks/8889292, customerstocks/8889293, customerstocks/8889294, customerstocks/8889295, customerstocks/8889296, customerstocks/8889297, customerstocks/8889298, customerstocks/8889299, customerstocks/8889300, customerstocks/8889301, customerstocks/8889302, customerstocks/8889303, customerstocks/8889304, customerstocks/8889305, customerstocks/8889306, customerstocks/8889307, customerstocks/8889308, customerstocks/8889309, customerstocks/8889310, customerstocks/8889311, customerstocks/8889312, customerstocks/8889313, customerstocks/8889314, customerstocks/8889315, customerstocks/8889316, customerstocks/8889317, customerstocks/8889318, customerstocks/8889319, customerstocks/8889320, customerstocks/8889321, customerstocks/8889322, customerstocks/8889323, customerstocks/8889324, customerstocks/8889325, customerstocks/8889326, customerstocks/8889327, customerstocks/8889328, customerstocks/8889329, customerstocks/8889330, customerstocks/8889331, customerstocks/8889332, customerstocks/8889333, customerstocks/8889334, customerstocks/8889335, customerstocks/8889336, customerstocks/8889337, customerstocks/8889338, customerstocks/8889339, customerstocks/8889340, customerstocks/8889341, customerstocks/8889342, customerstocks/8889343, customerstocks/8889344, customerstocks/8889345, customerstocks/8889346, customerstocks/8889347, customerstocks/8889348, customerstocks/8889349, customerstocks/8889350, customerstocks/8889351, customerstocks/8889352, customerstocks/8889353, customerstocks/8889354, customerstocks/8889355, customerstocks/8889356, customerstocks/8889357, customerstocks/8889358, customerstocks/8889359, customerstocks/8889360, customerstocks/8889361, customerstocks/8889362, customerstocks/8889363, customerstocks/8889364, customerstocks/8889365, customerstocks/8889366, customerstocks/8889367, customerstocks/8889368, customerstocks/8889369, customerstocks/8889370, customerstocks/8889371, customerstocks/8889372, customerstocks/8889373, customerstocks/8889374, customerstocks/8889375, customerstocks/8889376, customerstocks/8889377, customerstocks/8889378, customerstocks/8889379, customerstocks/8889380, customerstocks/8889381, customerstocks/8889382, customerstocks/8889383, customerstocks/8889384, customerstocks/8889385, customerstocks/8889386, customerstocks/8889387, customerstocks/8889388, customerstocks/8889389, customerstocks/8889390, customerstocks/8889391, customerstocks/8889392, customerstocks/8889393, customerstocks/8889394, customerstocks/8889395, customerstocks/8889396, customerstocks/8889397, customerstocks/8889398, customerstocks/8889399, customerstocks/8889400, customerstocks/8889401, customerstocks/8889402, customerstocks/8889403, customerstocks/8889404, customerstocks/8889405, customerstocks/8889406, customerstocks/8889407, customerstocks/8889408, customerstocks/8889409, customerstocks/8889410, customerstocks/8889411, customerstocks/8889412, customerstocks/8889413, customerstocks/8889414, customerstocks/8889415, customerstocks/8889416, customerstocks/8889417, customerstocks/8889418, customerstocks/8889419, customerstocks/8889420, customerstocks/8889421, customerstocks/8889422, customerstocks/8889423, customerstocks/8889424, customerstocks/8889425, customerstocks/8889426, customerstocks/8889427, customerstocks/8889428, customerstocks/8889429, customerstocks/8889430, customerstocks/8889431, customerstocks/8889432, customerstocks/8889433, customerstocks/8889434
Exception
Raven.Abstractions.Exceptions.IndexDoesNotExistsException: There is no reduce index named: 97
at Raven.Database.Storage.Esent.StorageActions.DocumentStorageActions.TouchIndexEtag(Int32 id)
at Raven.Storage.Esent.TransactionalStorage.Batch(Action`1 action)
at Raven.Database.Tasks.RemoveFromIndexTask.Execute(WorkContext context)
at Raven.Database.Indexing.IndexingExecuter.<>c__DisplayClass6.<ExecuteTask>b__5(IStorageActionsAccessor actions)
at Raven.Storage.Esent.TransactionalStorage.Batch(Action`1 action)
at Raven.Database.Indexing.IndexingExecuter.ExecuteTask(HashSet`1 indexIds, Reference`1 foundWorkLocal)
at Raven.Database.Indexing.IndexingExecuter.<>c__DisplayClass2.<ExecuteTasksInternal>b__0(IStorageActionsAccessor actions)
at Raven.Storage.Esent.TransactionalStorage.ExecuteBatch(Action`1 action, EsentTransactionContext transactionContext)
at Raven.Storage.Esent.TransactionalStorage.Batch(Action`1 action)
at Raven.Database.Indexing.IndexingExecuter.ExecuteTasksInternal()
at Raven.Database.Indexing.IndexingExecuter.ExecuteTasks()
at Raven.Database.Indexing.AbstractIndexingExecuter.Execute()
There is no index named 97 and there are no stocks with those ids in the database.
How do I resolve this issue?
I solved this issue by reinstalling ravendb on hosting server
Ran in to this on an old legacy system. Upgrading to the latest 3.0 series fixed the problem without removing everything. We did have to reindex though.
Related
Hibernate QueryException Named parameter not bound error
I keep getting the error org.hibernate.QueryException: Named parameter not bound : item when I start my transaction in JPA using EntityManager createNativeQuery. I have my code below utilizing the entity manager, along with my embeddedID class (for the composite key) and my persistence entity bean. Is there a problem in my query syntax? I am not sure as I've tried multiple ways of formatting the sql (coming from a properties file where there resides multiple sqls used throughout the project, and attempting to persist data to an oracle db). I am not sure why I keep falling on this error. I want to persist this data to my oracle database but this error keeps preventing that. Query from query.properties file: insertPromoData =INSERT INTO TEST.U_USER_PROMO (ITEM, LOC, WK_START, NUMBER_OF_WEEKS, TYPE, FCSTID, QTY, U_TIMESTAMP) VALUES (:item, :location, :wkStart, :numberOfWeeks, :type, :fcstId, :quantity, SYSDATE) Embeddedable Class for establishing composite primary key on the target table: #Embeddable public class PromoID implements Serializable { #Column(name = "ITEM") private String item; #Column(name = "LOC") private String loc; #Column(name = "WK_START") private Date weekStart; #Column(name = "TYPE") private int type; #Column(name = "FCSTID") private String forecastId; #Column(name = "U_TIMESTAMP") private Timestamp insertTS; public PromoID() { } public PromoID (String item, String loc, Date weekStart, int type, String forecastId, Timestamp insertTS) { this.item = item; this.loc = loc; this.weekStart = weekStart; this.type = type; this.forecastId = forecastId; this.insertTS = insertTS; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public String getLoc() { return loc; } public void setLoc(String loc) { this.loc = loc; } public Date getWeekStart() { return weekStart; } public void setWeekStart(Date weekStart) { this.weekStart = weekStart; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getForecastId() { return forecastId; } public void setForecastId(String forecastId) { this.forecastId = forecastId; } public Timestamp getInsertTS() { return insertTS; } public void setInsertTS(Timestamp insertTS) { this.insertTS = insertTS; } //removed hashcode and equals methods for simplicity Persistence Entity Bean: #Entity #Table(name = "U_USER_PROMO") public class InsertPromoData { #EmbeddedId private PromoID id; /*#Column(name="BATCH_ID") String batchID;*/ #Column(name="ITEM") String item; #Column(name="LOC") String loc; #Column(name="WK_START") String weekStart; #Column(name="TYPE") String type; #Column(name="FCSTID") String forecastId; #Column(name="U_TIMESTAMP") String insertTS; #Column(name="NUMBER_OF_WEEKS") String numberOfWeeks; #Column(name="QTY") String qty; #Id #AttributeOverrides( { #AttributeOverride(name = "item",column = #Column(name="ITEM")), #AttributeOverride(name = "loc", column = #Column(name="LOC")), #AttributeOverride(name = "weekStart", column = #Column(name="WK_START")), #AttributeOverride(name = "type", column = #Column(name="TYPE")), #AttributeOverride(name = "forecastId", column = #Column(name="FCSTID")) } ) public PromoID getId() { return id; } public void setId(PromoID id) { this.id = id; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public String getLoc() { return loc; } public void setLoc(String loc) { this.loc = loc; } public String getWeekStart() { return weekStart; } public void setWeekStart(String weekStart) { this.weekStart = weekStart; } public String getNumberOfWeeks() { return numberOfWeeks; } public void setNumberOfWeeks(String numberOfWeeks) { this.numberOfWeeks = numberOfWeeks; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getForecastId() { return forecastId; } public void setForecastId(String forecastId) { this.forecastId = forecastId; } public String getQty() { return qty; } public void setQty(String qty) { this.qty = qty; } public String getInsertTS() { return insertTS; } public void setInsertTS(String insertTS) { this.insertTS = insertTS; } } My dao OracleImpl.java using EntityManager for persisting: public void insertPromoData(List<InsertPromoData> insertData) { logger.debug("Execution of method insertPromoData in Dao started"); EntityManager em = emf.createEntityManager(); try { em.getTransaction().begin(); System.out.println("Beginning transaction for insertPromoData"); Query query = em.createNativeQuery(env.getProperty("insertPromoData")); for (InsertPromoData promoData : insertData) { query.setParameter("item", promoData.getItem()); query.setParameter("location", promoData.getLoc()); query.setParameter("wkStart", promoData.getWeekStart()); query.setParameter("numberOfWeeks", promoData.getNumberOfWeeks()); query.setParameter("type", promoData.getType()); query.setParameter("fcstId", promoData.getForecastId()); query.setParameter("quantity", Double.valueOf(promoData.getQty())); } query.executeUpdate(); System.out.println("Data for promo persisted"); em.getTransaction().commit(); } catch(Exception e) { logger.error("Exception in beginning transaction"); e.printStackTrace(); } finally { em.clear(); em.close(); } logger.debug("Execution of method insertPromoData in Dao ended"); } PromoValidator.java class: List <InsertPromoData> insertPromos = new ArrayList<>(); promo.forEach(record -> { if (record.getErrorList().size() == 0) { rowsSuccessful++; record.setItem(record.getItem()); record.setLoc(record.getLoc()); record.setNumber_Of_Weeks(record.getNumber_Of_Weeks()); record.setForecast_ID(record.getForecast_ID()); record.setType(record.getType()); record.setUnits(record.getUnits()); record.setWeek_Start_Date(record.getWeek_Start_Date()); insertPromos = (List<InsertPromoData>) new InsertPromoData(); for (InsertPromoData insertPromoData : insertPromos) { insertPromoData.setItem(record.getItem()); insertPromoData.setLoc(record.getLoc()); insertPromoData.setWeekStart(LocalDate.parse(record.getWeek_Start_Date())); insertPromoData.setNumberOfWeeks(Integer.parseInt(record.getNumber_Of_Weeks())); insertPromoData.setType(Integer.parseInt(record.getType())); insertPromoData.setForecastId(record.getForecast_ID()); insertPromoData.setQty(Double.parseDouble(record.getUnits())); } } else { if (rowsFailure == 0) { Util.writeHeaderToFile(templateCd, errorFile); } rowsFailure++; Util.writeErrorToFile(templateCd, errorFile, record, record.getErrorList()); } }); errorFile.close(); successFile.close(); OracleImpl.insertPromoData(insertPromos);
One of the reason this can happen is when insertData List you are passing is empty. If I use below code ( please note that I have removed few columns to simplify it on my test environment with H2 database) - I get the error you described if empty list is passed and that's because there is indeed nothing to bind for the name parameter as the loop is not executed. try { em.getTransaction().begin(); System.out.println("Beginning transaction for insertPromoData"); Query query = em.createNativeQuery( "INSERT INTO U_USER_PROMO (ITEM, LOC, WK_START, NUMBER_OF_WEEKS, TYPE, FCSTID, QTY) VALUES (:item, :location, :wkStart, :numberOfWeeks, :type, :fcstId, :quantity)"); for (InsertPromoData promoData : insertData) { query.setParameter("item", promoData.getId().getItem()); query.setParameter("location", promoData.getId().getLoc()); query.setParameter("wkStart", promoData.getId().getWeekStart()); query.setParameter("numberOfWeeks", promoData.getNumberOfWeeks()); query.setParameter("type", promoData.getId().getType()); query.setParameter("fcstId", promoData.getId().getForecastId()); query.setParameter("quantity", Double.valueOf(promoData.getQty())); } query.executeUpdate(); System.out.println("Data for promo persisted"); em.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); } finally { em.clear(); em.close(); } The error I get is org.hibernate.QueryException: Named parameter not bound : item at org.hibernate.query.internal.QueryParameterBindingsImpl.verifyParametersBound(QueryParameterBindingsImpl.java:210) at org.hibernate.query.internal.AbstractProducedQuery.beforeQuery(AbstractProducedQuery.java:1425) at org.hibernate.query.internal.NativeQueryImpl.beforeQuery(NativeQueryImpl.java:249) at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1610) at com.danielme.blog.nativesql.dao.UserDao.insertPromoData(UserDao.java:99) However - if I pass non-empty list - this works as expected SQLCustomQuery:72 - Starting processing of sql query [INSERT INTO U_USER_PROMO (ITEM, LOC, WK_START, NUMBER_OF_WEEKS, TYPE, FCSTID, QTY) VALUES (:item, :location, :wkStart, :numberOfWeeks, :type, :fcstId, :quantity)] AbstractFlushingEventListener:74 - Flushing session
I also encountered same problem. I noticed that I was defining the parameter in the query but I was not setting its value in: query.setParameter(parameterToBeSet,parameterValue) For example, String hql = "FROM COLLEGE FETCH ALL PROPERTIES WHERE studentId = :studentId AND departmentId = :departmentId AND studentName = :studentName"; DBConnectionManager.getInstance().invokeCallableOnSessionMasterDB(session -> { Query<CollegeEntity> query = session.createQuery(hql); query.setParameter("studentId", studentId); query.setParameter("departmentId", departmentId); values.addAll(query.list()); }); As you can see the student name value was not set. So, after adding: query.setParameter("studentName", studentName); It got solved.
GETRequest : localhost:8080/getbyCity/chennai,mumbai,kolkata - error ---> when I send this request I got------->"Hibernate QueryException Named parameter not bound error". Answer: when we send list of parameter we should mention the "/" at the End. ((( localhost:8080/getbyCity/chennai,mumbai,kolkata/ ))). Set the bound using "/".
In my case I have put same parameter name to the procedure as: #Param("managementAccess") Boolean managementAccess, #Param("managementAccess") String dealerCode, #Param("managementAccess") String dealerName, Here the parameter name is different but inside string the name is same. Solution is: #Param("managementAccess") Boolean managementAccess, #Param("dealerCode") String dealerCode, #Param("dealerName") String dealerName,
Select or SelectList: I Want to include the entire entity
I am querying a list of objects, and then correlating them with a subquery. I want to return the results of the subquery, as well as the root entity. But I can't figure out how to actually return the root entity, I can only return individual properties of it. Specifically, this works: this.Session.QueryOver<MediaFile>(() => mediaFile) .SelectList(list => list.Select(mf => mf.Id)); But this does not: this.Session.QueryOver<MediaFile>(() => mediaFile) .SelectList(list => list.Select(mf => mf)); I get the following error: Could not resolve property : of MediaFile Does anyone know how I can include the entity as a property in the list? Here's my complete example: // My target class private class MediaFileAndCount { // I can successfully populate these fields. public long MediaFileId { get; set; } public int DistinctPlaylistCount { get;set; } // But I want to populate this field! public MediaFile MediaFile { get; set; } } private void TrySingleQuery() { MediaFile mediaFile = null; PlaylistEntry playlistEntry = null; MediaFileAndCount mfc = null; var subQuery = QueryOver.Of<PlaylistEntry>(() => playlistEntry) .Where(() => playlistEntry.MediaFile.Id == mediaFile.Id) .Select(Projections.CountDistinct<PlaylistEntry>(p => p.Playlist)); var query = this.Session.QueryOver<MediaFile>(() => mediaFile) .SelectList(list => list .Select(mf => mf.Id).WithAlias(() => mfc.MediaFileId) .Select(Projections.SubQuery(subQuery)).WithAlias(() => mfc.DistinctPlaylistCount) // .Select(mf => mf).WithAlias(() => mfc.MediaFile) // This line fails ) .TransformUsing(Transformers.AliasToBean<MediaFileAndCount>()); var results = query.List<MediaFileAndCount>(); }
another way to query it var allMediaFiles = session.QueryOver<MediaFile>().Where(...).ToFuture(); // just get the MediaFiles into sessionCache var results = session.QueryOver<PlaylistEntry>() .Where(p => p.MediaFile...) .SelectList(list => list .GroupBy(p => p.MediaFile.Id) .CountDistinct(p => p.Playlist)) .ToFuture<object[]>() .Select(a => new MediaFileAndCount { MediaFile = session.Get<MediaFile>((long)a[0]), DistinctPlaylistCount = (int)a[1] }) .ToList(); foreach (var mediaFile in allMediaFiles.Except(results.Select(r => r.MediaFile))) { results.Add(new MediaFileAndCount { MediaFile = mediaFile }); }
nHibernate ByCode Mapping - How to map ManyToMany entirely by convention?
I have defined this mapping: public class Mapping : ConventionModelMapper { public Mapping() { IsRootEntity((type, declared) => { return !type.IsAbstract && new[] { typeof(Entity<Guid>), typeof(CommonEntity) }.Contains(type.BaseType); }); IsEntity((x, y) => typeof(Entity<Guid>).IsAssignableFrom(x) && !x.IsAbstract && !x.IsInterface); IsSet((mi, wasDeclared) => { var propertyType = mi.GetPropertyOrFieldType(); return propertyType.IsGenericType && typeof(System.Collections.Generic.ISet<>).IsAssignableFrom(propertyType.GetGenericTypeDefinition()); }); IsManyToMany((mi, wasDeclared) => { var propertyType = mi.GetPropertyOrFieldType(); var containingType = mi.ReflectedType; if (typeof(System.Collections.Generic.ISet<>).IsAssignableFrom(propertyType.GetGenericTypeDefinition())) { var referenceType = propertyType.GetGenericArguments()[0]; return true; return !referenceType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Any(p => p.PropertyType.IsAssignableFrom(containingType)); } return false; }); Class<Entity<Guid>>(x => { x.Id(c => c.Id, m => m.Generator(Generators.GuidComb)); x.Version(c => c.Version, (vm) => { }); }); BeforeMapClass += OnBeforeMapClass; BeforeMapManyToOne += OnBeforeMapManyToOne; BeforeMapSet += OnBeforeMapSet; BeforeMapManyToMany += OnBeforeMapManyToMany; Class<CommonEntity>(x => { x.Property(c => c.DateCreated, m => m.Type<UtcDateTimeType>()); x.Property(c => c.DateModified, m => m.Type<UtcDateTimeType>()); }); } private void OnBeforeMapManyToMany(IModelInspector modelInspector, PropertyPath member, IManyToManyMapper collectionRelationManyToManyCustomizer) { collectionRelationManyToManyCustomizer.Column(member.LocalMember.GetPropertyOrFieldType().GetGenericArguments()[0].Name + "Id"); } private void OnBeforeMapSet(IModelInspector modelInspector, PropertyPath member, ISetPropertiesMapper propertyCustomizer) { propertyCustomizer.Key(k=>k.Column(member.GetContainerEntity(modelInspector).Name + "Id")); propertyCustomizer.Cascade(Cascade.Persist); if (modelInspector.IsManyToMany(member.LocalMember)) { propertyCustomizer.Table(member.GetContainerEntity(modelInspector).Name + member.LocalMember.GetPropertyOrFieldType().GetGenericArguments()[0].Name); } } private void OnBeforeMapManyToOne(IModelInspector modelInspector, PropertyPath member, IManyToOneMapper propertyCustomizer) { propertyCustomizer.Column(member.LocalMember.Name + "Id"); } private void OnBeforeMapClass(IModelInspector modelInspector, Type type, IClassAttributesMapper classCustomizer) { classCustomizer.Table('['+ type.Name + ']'); } } An I am having a problem with a many to many relationship. I have User, UserPermission and Permission. When I am saving a user after attaching a Permission to it it generates this SQL: exec sp_executesql N'UPDATE [Permission] SET UserId = #p0 WHERE Id = #p1',N'#p0 uniqueidentifier,#p1 uniqueidentifier',#p0='57A2CD87-4A79-4131-B9CE-A1060168D520',#p1='9D99D340-1B63-4291-B55A-6127A8F34FC9' When it should be like: exec sp_executesql N'INSERT INTO UserPermission (UserId, PermissionId) VALUES (#p0, #p1)',N'#p0 uniqueidentifier,#p1 uniqueidentifier',#p0='2C670A01-C2E6-46A3-A412-A1060168F976',#p1='9D99D340-1B63-4291-B55A-6127A8F34FC9' When I add a specific class mapping for User: Class<User>(classMapper => { classMapper.Set(x => x.Permissions, map => { //map.Key(k => k.Column("UserId")); //map.Table("UserPermission"); }, r => r.ManyToMany(m => {})); }); I can leave out the key and table definition and include the ManyToMany without the column call and it works. But it does the same same thing as my BeforeManyToMany event handler. If I drop the whole Class thing the BeforeMapManyToMany event is not fired and nHibernate thinks I've got a UserId on my Permission table. Heres User: public class User : CommonEntity { protected User() { Permissions = new HashSet<Permission>(); } public User(User createdBy) : base(createdBy) { Permissions = new HashSet<Permission>(); } public ISet<Permission> Permissions { get; protected set; } }
After poking around in the source code I realised the problem was that IsOneToMany was checked against the property when defining the set before IsManyToMany. I just needed to define IsOneToMany and it worked without any explicit mappings. IsOneToMany((mi, wasDeclared) => { var propertyType = mi.GetPropertyOrFieldType(); return ModelInspector.IsEntity(propertyType); });
RavenDB String.Contains on multi map index
So far I have an index like this: public class Animals_Search : AbstractMultiMapIndexCreationTask<Animals_Search.Result> { public class Result { public object[] Content { get; set; } } public Animals_Search() { AddMap<Dog>(a => from b in a select new Result { Content = new object[] { b.Name, b.Breed} }); AddMap<Cat>(a=> from bin docs select new Result { Content = new object[] { b.Name, b.Breed} }); Index(x => x.Content, FieldIndexing.Analyzed); } } And a query like this: session.Query<Animals_Search.Result, Animals_Search>() .Search(a => a.Content, match) .As<Animal>() .ToList(); This works if I provide search terms like "Collie" or "Terrier", but not "Coll" or "Terr" How do I rewrite the query to work something like String.Contains("Terr")?
RavenDB make it hard to do contains query, because for the most part, they aren't needed. What you probably want is to do a StartsWith, instead. session.Query<Animals_Search.Result, Animals_Search>() .Where(a => a.Content.StartsWith(match)) .As<Animal>() .ToList();
Fluent NHibernate: testing collection mapping with CheckList
I've used Fluent NH in some projects but I'm having some problems with using the PersistenceSpecification class for testing a collection mapping. Here's the code for my classes (I'm just putting here the collection definition): public class Ocorrencia : EntityWithAction, IHasAssignedId<Int32> { private IList<Intervencao> _intervencoes = new List<Intervencao>(); public IEnumerable<Intervencao> Intervencoes { get{ return new ReadOnlyCollection<Intervencao>( _intervencoes ); } set { _intervencoes = new List<Intervencao>( value ); Contract.Assume(_intervencoes != null); } } public void ModificaEstado(Intervencao intervencao ){ //some checks removed intervencao.Ocorrencia = this; _intervencoes.Add(intervencao); } //more code removed } public class Intervencao : EntityWithAction, IHasAssignedDomainAction { //other code remove internal Ocorrencia Ocorrencia { get; set; } } And here's the mappings (only the important things): public class IntervencaoMapping: ClassMap<Intervencao> { public IntervencaoMapping() { WithTable("Intervencoes"); Not.LazyLoad(); Id(intervencao => intervencao.Id) .ColumnName("IdIntervencoes") .WithUnsavedValue(0) .SetGeneratorClass("identity"); Map(intervencao => intervencao.Guid, "Guid") .Not.Nullable(); Version(ent => ent.Version) .ColumnName("Version"); References(ent => ent.Action, "IdAccao") .Cascade .SaveUpdate(); Map(intervencao => intervencao.TipoEstado, "TipoEstado") .CustomTypeIs(typeof (TipoEstado)) .CustomSqlTypeIs("integer"); Map(intervencao => intervencao.Observacoes, "Observacoes"); References(intervencao => intervencao.Ocorrencia, "IdOcorrencias") .Not.LazyLoad(); } } public class OcorrenciaMapping: ClassMap<Sra.Ocorrencias.Ocorrencia> { public OcorrenciaMapping() { WithTable("Ocorrencias"); Not.LazyLoad(); Id(ocorrencia => ocorrencia.Id) .ColumnName("IdOcorrencias") .WithUnsavedValue(0) .SetGeneratorClass("identity"); Map(ocorrencia => ocorrencia.Guid, "Guid") .Not.Nullable(); Version(ocorrencia => ocorrencia.Version) .ColumnName("Version"); Map(ocorrencia => ocorrencia.Descricao) .ColumnName("Descricao"); Map(ocorrencia => ocorrencia.Nif, "Nif") .Not.Nullable(); Map(ocorrencia => ocorrencia.TipoOcorrencia, "TipoOcorrencia") .CustomTypeIs(typeof(TipoOcorrencia)) .CustomSqlTypeIs("integer"); Map(ocorrencia => ocorrencia.BalcaoEntrada, "Balcao") .CustomTypeIs(typeof(TipoBalcao)) .CustomSqlTypeIs("integer") .Not.Nullable(); References(ocorrencia => ocorrencia.Organismo, "IdOrganismos") .Cascade.None() .Not.Nullable(); HasMany(ocorrencia => ocorrencia.Intervencoes) .Access.AsCamelCaseField(Prefix.Underscore) .AsBag() .Cascade .All() .KeyColumnNames.Add("IdOcorrencias") .Not.LazyLoad(); } } As you can see, Interncao objects are added through the ModificaEstado method which ensures that Ocorrencia reference on Intervencao "points" to a reference of Ocorrencia. Now, how do I test this relationship with the PersistenceSpecification object? I've ended up with the following code: [Test] public void Test() { using (var session = _factory.GetSession()) { using (var tran = session.BeginTransaction()) { var accao = CreateAction(); session.Save(accao); var organismo = CreateOrganismo(); session.Save(organismo); var intervencao = CreateIntervencao(); ((IHasAssignedDomainAction)intervencao).SetActionTo(accao); var intervencoes = new List<Intervencao> {intervencao}; new PersistenceSpecification<Ocorrencia>(session) .CheckProperty(e => e.Nif, _nif) .CheckProperty( e =>e.Organismo, organismo) .CheckProperty( e => e.Descricao, _descricao) .CheckProperty( e => e.TipoOcorrencia, TipoOcorrencia.Processo) .CheckList( e => e.Intervencoes, intervencoes) .VerifyTheMappings()); tran.Rollback(); } } } Since IdOcorrencia is defined as an external key in table Intervencoes, the previous code fails because it tries to insert the intervencoes list with IdOcorrencia set to null. If I remove the external key, then the test works fine, but I believe that I shouldn't be doing that. I'm probably doing something wrong but I'm not sure on what that is. So, can anyone be kind enough and give me a hint on how to solve this? thanks guys. Luis
The problem was that I was using an old version of the fluent nhibernate. recente versions have overrides which let you solve this kind of problem: http://www.mail-archive.com/fluent-nhibernate#googlegroups.com/msg06121.html