RavenDB index doesnt show new data - asp.net-mvc-2

I have a model defined as
public class Department
{
[ScaffoldColumn(false)]
public object Id { get; set; }
[Required(ErrorMessage = "Department Name is required")]
[StringLength(25)]
[DisplayName("Department Name")]
public string Name { get; set; }
[DefaultValue(true)]
[DisplayName("Active?")]
public bool Active { get; set; }
}
i have added one record using the asp.net view. To retrieve the records i have created a simple index "DepartmentIndex" as
from dept in docs.Departments
select new {dept.Id,dept.Name}
To fetch the records I am using the following linq query
var depts = dbSession.Query<Department>("DepartmentIndex").OrderByDescending(x => x.Id);
Till here everything is fine. I can see the first record I have added on my view page. But, when I start adding more records i don't see the newly added ones. What have I missed?

RavenDB updates indexes in the background, so the results might be stale. See the documentation here for more info. In the client API you need to call the function WaitForNonStaleResults, to do this.

I was using build #133 i upgraded to #140 now, this doesn't seems to be a problem.

Related

Cannot insert explicit value for identity column - into related table

I have a database first model.
My application UI provides a group of checkboxes, one for each value in Data_Type.
When the user checks one, I expect a row to be added in BUS_APPL_DATA_TYPE,
however I'm getting an error about Cannot insert explicit value for identity column in DATA_TYPE (And I absolutely do not actually want to insert data in this table)
My EF Model class for BUS_APPL has this property
public ICollection<BusApplDataType> BusApplDataType { get; set; }
And that EF Model class looks like
public partial class BusApplDataType
{
public int BusApplId { get; set; }
public int DataTypeId { get; set; }
[Newtonsoft.Json.JsonIgnore]
public BusAppl BusAppl { get; set; }
public DataType DataType { get; set; }
}
What exactly do I need to add to the BusApplDataType collection to get a record to be inserted in BUS_APPL_DATA_TYPE?
Edit:
At a breakpoint right before SaveChanges.
The item at index 2 is an existing one and causes no issues.
The item at index 3 is new. Without this everything updates fine. There is a DATA_TYPE with id 5 in the database.
The surrounding code, if it helps.
[HttpPut("{id}")]
public IActionResult Update(int id, [FromBody] BusAppl item)
{
...
var existing = _context.BusAppl.FirstOrDefault(t => t.Id == id);
...
existing.BusApplDataType = item.BusApplDataType; //A bunch of lines like this, only this one causes any issue.
...
_context.BusAppl.Update(existing);
_context.SaveChanges();
return new NoContentResult();
}
My issue was that I needed to use my context to look up the actual entity, using info passed, instead of using the one with all the same values that was passed into my api directly.

Get the current logged in IdentityUser?

I'm trying to create an application where I'm using Windows Identity and Entity Framework Code First. So I'm creating a custom class to save some data.
public class Order {
public string Name { get; set; }
public DateTime CreatedDate { get; set; }
public IdentityUser User { get; set; }
}
Now I'm trying to link the user table to the order table (as generated by Entity Framework). So that I can do Order.User to get user info on the user who created the Order.
I want to create a new order using
new Order {
Name = "Test",
CreatedDate = new DateTime(2014, 3, 30),
User = <What goes here?>
}
Now how to I get "IdentityUser" of the currently logged in user? Or am I going about this the wrong way?
You can get the current user from User.Identity inside of a controller, and HttpContext.Current.User.Identity from outside. Check this: ASP.NET MVC 5 - Identity. How to get current ApplicationUser

In Entity Framework Code First for how do I create new records for two related 1 to common M posted data relationships

I am using EF Code First 5.
I have 3 entities/POCO classes - Proposal, Document and Template that are related.
Proposal has a M to M relationship with Document table.
Template has a M to M relationship with Document table.
Here are my POCO C# classes
public class Document {
public int Id { get; set; }
public string FileName { get; set; }
public ICollection<Proposal> Proposals { get; set; }
public ICollection<Template> Templates { get; set; }
}
public class Proposal {
public int Id { get; set; }
public string Title{ get; set; }
public string Description { get; set; }
public ICollection<Document> Documents { get; set; }
}
public class Template {
public int Id { get; set; }
public string Title{ get; set; }
public string Description { get; set; }
public ICollection<Document> Documents { get; set; }
}
In my front end MVC app the user creates a proposal and adds documents to it.
I then receive the posted data in my MVC action method and add all the document to the proposal Documents collection
proposal.Description = model.Description;
proposal.Documents = GetDocumentsFromPostedFiles(model.Files);
db.Entry(proposal).State = EntityState.Added;
db.SaveChanges();
This work perfectly as the documents get assigned unique ids when saving to the db and are linked to my proposal.
However in the same screen with the same action the user has the option to save the documents he adds to the proposal to a new template.
So I want the Template table to get the reference the same documents that is being added to the Proposal in my one MVC action method.
I receive the posted data
- the 1 Proposal.
- Many Documents
- the new Template Title, Description
so what I want to update is all 3 tables with this posted data.
I tried the following:
proposal.Description = model.Description;
proposal.Documents = GetDocumentsFromPostedFiles(model.Files);
template.Description = model.TemplateDescription;
template.Documents = proposal.Documents();
db.Entry(proposal).State = EntityState.Added;
db.Entry(template).State = EntityState.Added;
db.SaveChanges();
This obviously updates incorrectly since the new unadded Documents have a Document id not set (value is default of 0) since the database will set it in the database after the db.SaveChanges so when I run it the templates' document ids' are incorrectly saved as 0.
How do I tell Entity Framework the template object's documents are related to the just added proposal documents?
I use the starting point of the 1 to M of either proposal or template to tell entity framework to add them to the database but as in my case since I have two 1 to M relationships how do I tell EF that the two M tables are in fact the same table when I do my initial db.SaveChanges?
Any other possible solution for this? I can only think of saving the proposal to the database first and reading all the just added documents with their primary key created ids from the database and then adding them to my Template.
This would result in a db.SaveChanges , Linq db Fetch and db.SaveChanges again where I would rather want to do this in one db.SaveChanges.
Call SaveChanges() after the proposal initialization:
proposal.Description = model.Description;
proposal.Documents = GetDocumentsFromPostedFiles(model.Files);
db.Entry(proposal).State = EntityState.Added;
db.SaveChanges();
template.Description = model.TemplateDescription;
template.Documents = proposal.Documents;
db.Entry(template).State = EntityState.Added;
db.SaveChanges();

Entity Framework Code First - Restoring collections of the same type

I'm using Entity Framework Code First. The class i'm trying to create contains two collections (of the same type). I'm having problem recovering my respective collections.
My classes look like this:
public class Destination
{
public int DestinationId { get; set; }
public string Name { get; set; }
public List<Lodging> Lodgings { get; set; }
public List<Lodging> Lodgings2 { get; set; }
}
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public Destination Destination { get; set; }
}
I created a new Destination, then I reopened (closed & opened) the database connection. When I retrieve the destination, my collections (dest.Lodgings and dest.Lodgings2) are null. How do I restore the respective collections? If my class only has one collection of a particular type, I could do the following:
var lodgings = context.Lodgings.Where(l => l.Destination.DestinationId == destId).ToList();
I can see that the relationships are maintained in the database schema (Destination_DestinationId1 and Destination_DestinationId2) but I don't seem to be able to get to them.
Any suggestion would be appreciated.
In addition to using Include (as you've discovered) (which loads the related data from the db at the same time the destination is retrieved) you can also retreive the lodgings after the fact. So if you query for the destination and then you want the lodgings, that's possible. One way is called explicit loading where you will use a Load method. The other is with lazy loading, which requires that your classes be set up a particular way and just the mere mention of the Lodgings property will trigger the call to the database to retrieve them.
there's a great blog post on the Ef team blog about the various ways to load related data with DbContext : http://blogs.msdn.com/b/adonet/archive/2011/01/31/using-dbcontext-in-ef-feature-ctp5-part-6-loading-related-entities.aspx
hth
Julie

How can I have Entity Framework return related objects with some defaults?

Say I have Project and Task EF Code first classes
public class Project
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Task> Tasks { get; set; }
}
public class Task
{
public int ID { get; set; }
public string Name { get; set; }
public int ProjectId { get; set; }
public bool IsDeleted {get; set;}
public virtual Project Project { get; set; }
}
Say I have
public void SomeAction()
{
Project p= repository.GetById(1);
var tasks = p.Tasks;
//var tasks = p.Tasks.Where(t=>t.IsDeleted==false);
}
I would like that my Tasks property on the Project class will always perform that filter on IsDeleted and just return that subset ... to avoid having to write that condition all over the place...
Any recommendations?
Edit:
Im using EF Code First
Add a discriminator to your model in the OnModelCreating method
modelBuilder.Entity<TEntity>().Map(m => m.Requires("IsDeleted").HasValue(false));
Caveats
You can no longer load deleted items (unless you map IsDeleted true to another entity, then you may lose your automatic filtering)
The poco class cannot have the IsDeleted property (discriminators cannot be mapped)
because the IsDeleted cannot be mapped you need to run raw SQL to delete the entity in the first place.
EF Code first = NO WAY. Just one from long list of features which is available in EDMX and it is completely missing in code first. Mapped condition from EDMX does this but it is still problematic because it is hardcoded and cannot be changed (= you will never be able to load deleted entities even if you want to unless you use another EDMX). The solution would be implementation of global filters in EF but EF doesn't have anything like that despite the fact that old Linq-to-entities have them at least for relations (DataLoadOptions.AssociateWith).
This is much more painful in relations where you cannot use eager or lazy loading without loading deleted entities to your application as well and do filtering in your application's memory.
In the Model Designer, select your Task entity, and bring up the Mapping Details window. This should show you the database table your entity is mapped to, and all the columns. Just under where it says "Maps to [YourTable]" you should see an option <Add a Condition>. This should let you set a condition like what you're looking for.