I've got a SL4 / WCF RIA Services / EF 4 application. I'm having trouble getting my Included entity into my SL4 data context.
In the server side service portion of the application, this is my method:
[Query(IsDefault = true)]
public IQueryable<ToolingGroup> GetToolingGroups()
{
var groups = this.ObjectContext.ToolingGroups.Include("MetaData").OrderBy(g => g.Name);
return groups; //breakpoint set here
}
I assigned it to the var groups to allow it to be inspected before the method returns. If I set a breakpoint before the method returns and add a line to my Watch window the MetaData is there:
groups.First().MetaData
When I let the method return and check it in the silverlight ui completed event MetaData is null.
void loadOperation_Completed(object sender, System.EventArgs e)
{
grid.ItemsSource = _toolingContext.ToolingGroups;
UpdateUI(); //breakpoint set here
}
When I do this in my watch window MetaData is null:
_toolingContext.ToolingGroups.First().MetaData
I checked to make sure the ToolingGroup returned by the call to .First() in both cases was the same entity and it was.
Why is MetaData lost (eg. null) between the service method and my ui method?
SOLUTION:
// The MetadataTypeAttribute identifies ToolingGroupMetadata as the class
// that carries additional metadata for the ToolingGroup class.
[MetadataTypeAttribute(typeof(ToolingGroup.ToolingGroupMetadata))]
public partial class ToolingGroup
{
// This class allows you to attach custom attributes to properties
// of the ToolingGroup class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class ToolingGroupMetadata
{
// Metadata classes are not meant to be instantiated.
private ToolingGroupMetadata()
{
}
public int Id { get; set; }
[Include] // Added so MetaData gets serialized
public MetaData MetaData { get; set; }
public Nullable<int> MetaDataId { get; set; }
public string Name { get; set; }
public ToolingCategory ToolingCategory { get; set; }
public int ToolingCategoryId { get; set; }
public EntityCollection<ToolingType> ToolingTypes { get; set; }
}
}
There are two layers at play here, EF and RIA Services. You've handled the EF part. Now you need to tell RIA services to include that property when it serializes your entities across the wire. In your metadata for the entity, add the [Include] attribute. Like this...
[MetadataType(typeof(ToolingGroup.MetaData)]
public partial class ToolingGroup {
private class MetaData {
// adding this attribute tells RIA services
// to also send this property across
[Include]
public MetaData MetaData { get; set; }
}
}
It's a bad coincidence that your type is called "Metadata", the ToolingGroup.MetaData class is the metadata that RIA services uses.
Related
I am building a NET Core MVC app that consumes an existing MS SQL database. Primary keys and foreign keys are already established and working correctly at the database level.
I followed the example in this article and used package manager console to reverse engineer the models and database context from the database. This seemed to work well. It resulted in all models being added to my app's Models folder including a robust database context class. The problem I'm having is that relational information about these entities isn't being populated at runtime. I'm getting nulls for related entities for which foreign keys are established both in the database and in the fluent API code generated by the scaffolding process.
I have two tables, Mode and Submode, that are related via foreign key.
Scaffolding generated these two classes for the above two tables:
public partial class Submode
{
public Submode()
{
Contact = new HashSet<Contact>();
}
public int Id { get; set; }
public int ModeId { get; set; }
public string Code { get; set; }
public bool Visible { get; set; }
public bool IsDefault { get; set; }
public Mode Mode { get; set; }
public ICollection<Contact> Contact { get; set; }
}
public partial class Mode
{
public Mode()
{
Contact = new HashSet<Contact>();
Submode = new HashSet<Submode>();
}
public int Id { get; set; }
public string Code { get; set; }
public bool Visible { get; set; }
public bool IsDefault { get; set; }
public ICollection<Contact> Contact { get; set; }
public ICollection<Submode> Submode { get; set; }
}
Scaffolding also generated this fluent API snippet in the database context:
modelBuilder.Entity<Submode>(entity =>
{
entity.HasIndex(e => e.Code)
.HasName("UQ__Submode__A25C5AA75D2A9AE7")
.IsUnique();
entity.Property(e => e.Code)
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false);
entity.HasOne(d => d.Mode)
.WithMany(p => p.Submode)
.HasForeignKey(d => d.ModeId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Submode_ModeId");
});
Every example I've read on setting foreign keys with fluent API show a similar pattern to the above snippets. But Mode comes back null for Submode.
Null at runtime
And I get a null reference exception in the returned view because I'm trying to display properties of the related Mode object. Am I missing some configuration or is there a problem with the scaffolded code?
UDPATE - as requested, here's the implementation that's fetching data from the database context.
public class SQLSubModeData : ISubModeData
{
private w4lkrContext _context;
public SQLSubModeData(w4lkrContext context)
{
_context = context;
}
public IQueryable<Submode> Get()
{
return _context.Submode.OrderBy(p => p.Id);
}
public Submode Get(int id)
{
return _context.Submode.FirstOrDefault(p => p.Id == id);
}
}
UPDATE (SOLVED) - Enabling lazy loading fixed the problem. Three steps got me there:
Installed Microsoft.EntityFrameworkCore.Proxies(2.1.2) via NuGet
Updated Startup.cs -> AddDbContext() method, as follows:
services.AddDbContext(options => options.UseLazyLoadingProxies().UseSqlServer(_configuration.GetConnectionString("W4LKR")));
Made all navigation properties virtual. This had to be done on every model in the app, not just the one being called in my example above. Errors are thrown if even one is left out.
But Mode comes back null for Submode.
Since your Navigation Properties aren't declared as virtual, you have disabled Lazy Loading, so EF will only populate your Navigation Properties if you do Eager Loading, or Explicit Loading.
See Loading Related Data
Overview
I am designing a mechanism for generating dynamic controls in an ASP.NET MVC application that uses ADO.NET Entity Framework. However, my question has nothing to do with MVC and a little to do with the Entity Framework. It is about comparing two object models.
Problem Statement
In my app, a user must have the ability to interact with Web page A to specify that he wants to add such and such HTML controls to Web Page B.
When he browses Web Page B next, he must see those controls and be able to use them.
What Is Not The Challenge
I have written the code to generate the controls. That was the easy part. I used the Tag Builder, Partial Views, HtmlHelper extensions and Display & Editor templates.
The Challenge
The challenge is in arriving at a database design and an object model generated by Entity Framework to hold the metadata about the controls that need to be generated.
I have come up with a database design as shown below:
You may ignore the User and Permissions tables. They are not relevant to our discussion.
Entity Framework generates the following entities based on the above database design.
Let's call my database design as Design Option A.
I would have wanted a design that looked more like this:
Let's call this second design as Design Option B.
The code (stripped down version) for this second option would look like this:
namespace DynamicControls
{
public class DynamicControlGroup
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Controller { get; set; }
public IEnumerable<string> Actions { get; set; }
public DateTime StartDate { get; set; }
public DateTime? EndDate { get; set; }
public User CreatedByUser { get; set; }
public DateTime CreationDateTime { get; set; }
public User LastModifiedBy { get; set; }
public DateTime ModificationDateTime { get; set; }
// Navigational
public ICollection<DynamicControl<T>> DynamicControls { get; set; }
}
public class DynamicControl<T>
{
public long Id { get; set; } //db Id
public string HtmlId { get; set; }
public bool ValueRequired { get; set; }
public virtual ControlType ControlType { get; protected set; }
// Every control is capable of having a default value but of a different
// type. Most controls have default values of type text (string). The
// multi-select ones (checkboxes, multi-select lists, etc.) have a default
// value of type IEnumerable<string>. So, I want to leave this generic.
// But I am not that hung-up on this. I am fine if I am required to move
// this property DefaultValue from the base class and make it a concrete
// (not generic) property for each individual child class.
// Mostly I just want the heirarchy. And before that, I want to know
// if it is a good idea to model this heirarchy. Or is it better to just
// work with what my Entity Framework produced for my db?
// Should I change my db? I can because I thought-up the design for
// those tables.
public virtual T DefaultValue { get; set; }
// Navigational
public DynamicControlGroup DynamicControlGroup { get; set; }
}
public class TextBox : DynamicControl<string>
{
public override ControlType ControlType
{
get
{
return DynamicControls.ControlType.TextBox;
}
}
public string Label { get; set; }
public int MaxLength { get; set; }
}
public class PasswordControl : TextBox
{
public override ControlType ControlType
{
get
{
return DynamicControls.ControlType.Password;
}
}
}
public class TextArea : TextBox
{
public override ControlType ControlType
{
get
{
return DynamicControls.ControlType.TextArea;
}
}
public int Rows { get; set; }
}
public class DropDownList: DynamicControl<string>
{
public override ControlType ControlType
{
get
{
return ControlType.DropDownList;
}
}
// I want something like this. That I should be able to say
//
// myDropDownListObject.Options...
//
// You'll notice that given my current database design, I have
// no direct way of accessing the options of a, say, drop down list.
// To do that, I have to make a round-about Linq query.
public ICollection<DynamicControlOption> Options { get; set; }
}
public class DynamicControlOption
{
public long Id { get; set; } // db Id
public string OptionHtmlId { get; set; }
public string OptionValue { get; set; }
public string OptionText { get; set; }
// Navigational property
public DynamicControl<IEnumerable<string>> TheControlWhoseOptionIAm { get; set; }
}
public class User
{
}
public class Permission
{
}
public enum ControlType
{
TextBox,
TextArea,
Password,
RadioButton,
Checkbox,
DropDownList,
MultiSelectList,
DatePicker,
TimePicker,
DateTimePicker
}
}
My Question
1) I feel that I'd like Design Option B better. Am I feeling right?
2) I know I can work with Design Option A just as fine but it'll involve a little round-about way to do some things. For example, to get all the options for a drop down list, there's not navigational property on the DropDownList class in Design Option A. I'll have to write a round-about Linq query to do that.
3) Is it possible to have Entity Framework come close to generating Design Option B? How? What changes will I need to make to my database design to achieve that?
Now we are working on a Project like this at our company...
If I got your meaning correctly and If I were you...I implemented inherited structure as my database design like below.
Now you Classes are inheritance but your database design is not.
I have removed Id in TextBox and I have put ControlId as PK and FK in the same time. (not just FK).
in fact,ControlId is both PK for TextBox and FK from DynamicControl
and also this way for PasswordControl and TextArea
and Now ControlId in TextBox is not Identity. It gets it's ControlId from DynamicControl
I also accept Design Option B .I'm always more comfortable than using Design Option A.in my idea It's true and main structure
I would like a DomainService as follows:
[EnableClientAccess]
public class FamilyService : DomainService
{
public IQueryable<Person> GetPeople() // for the time being fake out a set of people
{
var people = new[]{ new Person(), ... };
return people.AsQueryable();
}
}
The Person class should be simple enough:
public class Person
{
[Key]
public Guid Id { get; set; }
public Person Parent { get; set; }
public String Name { get; set; }
public Person[] Children { get; set; }
}
In the Silverlight client, the Person class that is generated does not include the Parent or Children properties. What am I missing?
(Perhaps I should point out that while this is obviously a mock example, I am planning on using a loosely coupled approach, that this mimics. In fact most of my data doesn't reside in a database at all A significant majority of the RIA samples use an end-to-end parity of model from the database to the UI, which is not an option in my case.)
Try adding the [Include] attribute to the Parent & Children properties.
public class Person
{
[Key]
public Guid Id { get; set; }
[Include]
public Person Parent { get; set; }
public String Name { get; set; }
[Include]
public Person[] Children { get; set; }
}
If the Person class is coming out of the DB (in your real world app) and you are using EF, then you need to force them to be loaded eagerly, using the .Include() method.
I am having problems databinding to EF code first. I need to be using Eager Loading, but I am running into some issues with databinding. I have the following classes:
public class Context : DbContext
{
DbSet<A> As;
DbSet<B> Bs;
DbSet<C> Cs;
}
public class A
{
public ICollection<B> Bs { get; set; }
public string Name { get; set; }
}
public class B
{
public ICollection<C> Cs { get; set; }
public string Name { get; set; }
}
public class C
{
public string Name { get; set; }
}
I am data binding Context.As to a Treeview, using the below code:
Context.As.Load();
tvItems.ItemsSource = Context.As.Local;
This works as expected, however, it does not automatically load the child properties, Bs, and subsequently, Cs. So, I found that lazy loading can help with this, like so:
Context.As.Load();
tvItems.ItemsSource = Context.As.Include(u=>u.Bs);
From my reading, this should automatically load at least the first level of child properties. However, this will not data bind, as I did not use .Local
.Include() returns IQueryable, which does not support .Local. I can use .ToList(), but this will not automatically update when I add items.
So, how the hell am I supposed to be doing this?
You could try this:
Context.As.Include(a => a.Bs).Load();
tvItems.ItemsSource = Context.As.Local;
Quick question for all y'all silverlight buffs..
I need to expose a custom POCO object through ria services.. Well kind of, i could probably get away with doing it over a vanilla web service.. so i dont mind if you tell me to do it over a non-RIA service
It's a bit like this:
public partial class Monkey
{
// etc..
// This is an entity framework entity
}
public class MonkeyCollection
{
// This is the POCO
public string MonthName { get; set; }
public Monkey MonkeyForMonth1 { get; set; }
public Monkey MonkeyForMonth2 { get; set; }
// Keep RIA services quiet about the lack of a "key"
[Key]
public int ID { get; set; }
}
// In my service class
public IEnumerable<MonkeyCollection> GetMonkeys()
{
// Churn the data like butter
}
This returns a collection of the POCO's but what it doesn't return is the embedded objects (monkey).
i.e. it returns the primitives (monthname, id) but not the custom objects..
And in fact intellisense in visual studio doesnt even seem to know about those properties on the class..
What should i do?
Thanks
Daniel
You need the IncludeAttribute and the AssociationAttribute.
public partial class Monkey
{
// etc..
// This is an entity framework entity
// fill this with the ID of the collection
public ParentMonkeyCollectionId { get; set; }
}
public class MonkeyCollection
{
// all the rest ...
[Include]
[Association("monkey1", "ID", "ParentMonkeyCollectionId")]
public Monkey MonkeyForMonth1 { get; set; }
[Include]
[Association("monkey2", "ID", "ParentMonkeyCollectionId")]
public Monkey MonkeyForMonth2 { get; set; }
}
Look here for a similar case and the explanation.
Also check WCF RIA Services and DTO with association for more details.
Moved it into it's own web service.. Just feels cleaner!