I have two objects.
[DataContract]
public class Record
{
[DataMember]
public string Id { get; set; }
}
And this class:
public class BatteryStatus : Record
{
[DataMember]
public DateTime RetrieveTime { get; set; }
}
I'm using Lite DB as a local NoSQL option to query and save the data. I'm needing to find and delete the values based after some time. Here's my code doing so:
var col = db.GetCollection<BatteryStatus>(CollectionName);
var test = col.FindAll()
.Where(x => x.Id == status.Id).ToList();
var result = col.Find(Query.EQ("Id", status.Id.ToString())).ToList();
Test returns with the with the object, but the result value doesn't. Lite DB only uses the Query or the BSONId as a way to delete an object. I don't have a BSON id attached to it (it's a referenced definition so I can't change it).
How can I use the "Query" function in order to get a nested value so I can delete it?
Classes has properties, BSON documents has fields. By default, LiteDB convert all property names to same name in BSON document except _id field which is document identifier.
If you want query using Linq, you will use properties expressions. If you are using Query object class, you must use field name.
var result = col.FindById(123);
// or
var result = col.FindOne(x => x.Id == 123);
// or
var result = col.FindOne(Query.EQ("_id", 123));
Find using _id always returns 1 (or zero) document.
I figured out the problem with LiteDB, since I was using the property name of "Id", the BSON interpreted that as the "_id" of the JSON object, and merging their two values. I solve the issue by renaming the "Id" property to something else.
Related
I'm in my first Code First project. I just learned how to add an index on two columns.
[Required]
[Index("IX_NameAndCity", 1, IsUnique = false)]
[MaxLength(900)]
public string Name { get; set; }
[Index("IX_NameAndCity", 2, IsUnique = false)]
[MaxLength(900)]
public string City { get; set; }
Does this look right? ^^^
Is there anything special in the LINQ to utilize these indexes or is it transparent? I was half expecting to see a choice in my LINQ for '.IX_NameAndCity'.
Here's what I'm doing now:
var property = _propertyRepository
.GetProperties()
.FirstOrDefault(x => x.Name == name && x.City == city);
Should it be something like:
var property = _propertyRepository
.GetProperties()
.FirstOrDefault(x => x.IX_NameAndCity.name == name && IX_NameAndCity.City == city);
Or does it automagically know there's an index?
Thanks all!
The index is created on the database server. Just like you don't want to explicitly refer to the index when you write a SQL query, you don't want to explicitly refer to the index when you write a LINQ query. And actually your entity won't have an IX_NameAndCity property. So simply use your first query:
var property = _propertyRepository
.GetProperties()
.FirstOrDefault(x => x.Name == name && x.City == city);
Entity Framework will construct the corresponding SQL query and pass it to the database server, and the database server will know it should (or possibly should not) use the index to speed up the query execution. It's transparent; don't worry about it.
I am using the Get API of Nest, but I don't know how to typecast the respone (IGetResponse) to the specific type of the document, something like this:
var response = client.Get<MyDocument>(documentId);
return response.Document(); // Or something like this that returns a MyDocument type
Also, is there a way to get the document for another unique field or only the Id is accepted?
response.Source holds document of type MyDocument.
As documentation says, you can use get api to get documents only by their ids.
You can tell elasticsearch to treat other field from document as Id.
With NEST you can do this as follows:
var indicesOperationResponse = client.CreateIndex(descriptor => descriptor
.Index(indexName)
.AddMapping<Document>(m => m.IdField(f => f.Path("uniqueValue"))));
client.Index(new Document{UniqueValue = "value1"});
var getResponse = client.Get<Document>(g => g.Id("value1"));
My document class:
public class Document
{
public string UniqueValue { get; set; }
}
I typically do mobile app development, which doesn't always have .Select. However, I've seen this used a bit, but I don't really know what it does or how it's doing whatever it does. It is anything like
from a in list select a // a.Property // new Thing { a.Property}
I'm asking because when I've seen code using .Select(), I was a bit confused by what it was doing.
.Select() is from method syntax for LINQ, select in your code from a in list select a is for query syntax. Both are same, query syntax compiles into method syntax.
You may see: Query Syntax and Method Syntax in LINQ (C#)
Projection:
Projection Operations - MSDN
Projection refers to the operation of transforming an object into a
new form that often consists only of those properties that will be
subsequently used. By using projection, you can construct a new type
that is built from each object. You can project a property and perform
a mathematical function on it. You can also project the original
object without changing it.
You may also see:
LINQ Projection
The process of transforming the results of a query is called
projection. You can project the results of a query after any filters
have been applied to change the type of the collection that is
returned.
Example from MSDN
List<string> words = new List<string>() { "an", "apple", "a", "day" };
var query = from word in words
select word.Substring(0, 1);
In the above example only first character from each string instance is selected / projected.
You can also select some fields from your collection and create an anonymous type or an instance of existing class, that process is called projection.
from a in list select new { ID = a.Id}
In the above code field Id is projected into an anonymous type ignoring other fields. Consider that your list has an object of type MyClass defined like:
class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
Now you can project the Id and Name to an anonymous type like:
Query Syntax:
var result = from a in list
select new
{
ID = a.Id,
Name = a.Name,
};
Method Syntax
var result = list.Select(r => new { ID = r.Id, Name = r.Name });
You can also project result to a new class. Consider you have a class like:
class TemporaryHolderClass
{
public int Id { get; set; }
public string Name { get; set; }
}
Then you can do:
Query Syntax:
var result = from a in list
select new TemporaryHolderClass
{
Id = a.Id,
Name = a.Name,
};
Method Syntax:
var result = list.Select(r => new TemporaryHolderClass
{
Id = r.Id,
Name = r.Name
});
You can also project to the same class, provided you are not trying to project to classes generated/created for LINQ to SQL or Entity Framework.
My summary is it takes results (or a subset of results) and allows you to quickly restructure it for use in the local context.
The select clause produces the results of the query and specifies the
"shape" or type of each returned element. For example, you can specify
whether your results will consist of complete Customer objects, just
one member, a subset of members, or some completely different result
type based on a computation or new object creation.
Source: http://msdn.microsoft.com/en-us/library/bb397927.aspx
There are a lot of possible uses for this but one is taking a complex object which of many other contains a property that is a string -- say Name -- and allows you to return an enumeration with just the entries of Name. I believe you can also do the opposite -- use that property ( for example) and create / return new type of object while passing in a property or properties.
It means "mapping". Map each element of a sequence to a transformed sequence. I hadn't comprehended its meaning before I looked at the image.
Where does the meaning of the word come from?
Simply, math! https://mathworld.wolfram.com/Projection.html
Using Orchard CMS, I am dealing with a record and a part proxy, but cannot figure out how to save it into the DB. In fact, I confess I don't even know how to get the items I'm trying to save into this paradigm. I was originally using enum's for choices:
MyEmum.cs:
public enum Choices { Choice1, Choice2, Choice3, Choice4 }
MyRecord.cs:
public virtual string MyProperty { get; set; }
MyPart.cs:
public IEnumerable<string> MyProperty
{
get
{
if (String.IsNullOrWhiteSpace(Record.MyProperty)) return new string[] { };
return Record
.MyProperty
.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries)
.Select(r => r.Trim())
.Where(r => !String.IsNullOrEmpty(r));
}
set { Record.MyProperty = value == null ? null : String.Join(",", value); }
}
Now, in my service class, I tried something like:
public MyPart Create(MyPartRecord record)
{
MyPart part = Services.ContentManager.Create<MyPart>("My");
...
part.MyProperty = record.MyProperty; //getting error here
...
return part;
}
However, I am getting the following error: Cannot implicitly convert 'string' to System.Collections.Generic.IEnumerable<string>'
Essentially, I am trying to save choices from a checkboxlist (one or more selections) as a comma-separated list in the DB.
And this doesn't even get me over the problem of how do I use the enum. Any thoughts?
For some background:
I understand that the appropriate way to handle this relationship would be to create a separate table and use IList<MyEnum>. However, this is a simple list that I do not intend to manipulate with edits (in fact, no driver is used in this scenario as I handle this on the front-end with a controller and routes). I am just capturing data and redisplaying it in the Admin view for statistical/historical purposes. I may even consider getting rid of the Part (considering the following post: Bertrand's Blog Post.
It should be:
part.MyProperty = new[] {"foo", "bar"};
for example. The part's setter will store the value on the record's property as a comma-separated string, which will get persisted into the DB.
If you want to use enum values, you should use the Parse and ToString APIs that .NET provide on Enum.
I have a linq query to a XML dataset, which when executed is generating a NullReferenceException.
XDocument dataDoc = XDocument.Load(new StringReader(e.Result));
var Genres = from genre in dataDoc.Descendants("genres")
where (!genre.Element("ID").IsEmpty)
select (string)genre.Element("id").Value + ',' + (string)genre.Attribute("name").Value + ',' + (string)genre.Attribute("url").Value;
foreach (string myGenre in Genres)
{
}
When executed, the Linq query works fine, but when the code attempts to iterate through the foreach loop, the NullReferenceException occurs.
Now, i think that the issue has to do with the XML data I am reading, which looks like the following:
<genres>
<translated>true</translated>
<genre name="1">
<id>28</id>
<url>http://url1</url>
</genre>
<genre name="2">
<id>12</id>
<url>http://url2</url>
</genre>
</genres>
Is the first child node, which is different in structure, causing the issue?
My class behind this shouldn't be an issue, but is the following (just in case):
public class Genre
{
public string ID { get; set; }
public string Name { get; set; }
public string URL { get; set; }
}
genre.Attribute("url") returns null, since there is no url attribute.
You need to call Element, not Attribute.
EDIT: Calling dataDoc.Descendants("genres") returns the single <genres> element, which is not what you want.
You need to call Descendants("genre") (singular) to get the individual <genre ...> elements.
You could also call dataDoc.Descendants("genres").Elements to get the elements inside the <genres> element.
SLaks has pointed out the mistake in using Attribute rather than Element, but there's another improvement you can make in your code. Currently you're using the Value property and then redundantly casting to string. If you just cast an XAttribute or XElement to string, then if the original reference is null, the result will be null as well, rather than an exception being thrown. There's no point in using Value and casting.