Identity Interface I should know better


17
Dec/09
1

Finding a place for WCF RIA in existing applications

Works with Entity Framework 4.0 CTP 2

My application so far ...

The premise of this application is to create a way for one or more people to create a common practice routine, set goals, and compare their progress.

I started this application with the intention of using Entity Framework 4 and RIA.

I started having problem with inserting from the server side, so I decided to start with a more basic model, and work my way into RIA and EF.

My data model looks like this

clip_image002

I started with the problem of how do I save disconnected entities across a service boundary.

I found that converting to Self Tracking Entities solved this problem very elegantly.

Problem Number 2
Option 1(The hard way)

I want the entire object graph on the client side, and I would like to be able dynamically generate a graph using a collection of Task Items.

I could do this by creating a silvlerlight class library sharing the objects(once they are converted to POCO’s) and using linking to share the objects between layers.

I would then have to build up the structure on the client side, using a series of async loads.

This is a lot of work. I have done it before, and every time I do it, I feel like I just wasted time I will never get back.

Option 2 - Use RIA and POCO.

I know that RIA sits in between the Server and the Client

clip_image004

(Shamelessly stolen from Brad Abrahams excellent RIA Services video)

So how do I add RIA to this project?

 

Setting up your POCO entities

I have an entity class for Tasks

namespace PracticeManager.Common.Entities
{
    public class Task
    {
        [Key]
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual DateTime CreatedTime { get; set; }
        public virtual DateTime ModifiedTime { get; set; }
        public virtual string Status { get; set; }
        public virtual string MeasurementUnit { get; set; }
        public virtual string UserName { get; set; }
        public virtual int? CommentId { get; set; }

        public ICollection<TaskItem> TaskItems { get; set; }
        public ICollection<Goal> Goals { get; set; }
        public Comment Comment { get; set; }
        public ICollection<Taunt> Taunts { get; set; }
        public ICollection<Challenge> Challenges { get; set; }
        public ICollection<Challenge> Challenges_1 { get; set; }

    }
}

I have my context class.

namespace PracticeManager.Server.Business.DataContext
{
    public class TaskDataContext : ObjectContext
    {
        private ObjectSet<Task> _tasks;

        public TaskDataContext(string connectionString)
            : base(connectionString, "PracticeModelContainer")
        {

        }

        public ObjectSet<Task> Tasks
        {
            get
            {
                return _tasks ?? (_tasks = base.CreateObjectSet<Task>());
            }

        }

    }
}

 

This covers the data loading portion.

Hooking up RIA Services

In your Web Project add a Domain Service class.

A wizard will appear, I avoided the wizard. I want to do this programmatically.

 

My domain class is pretty simple, for now I just want a list of tasks.

[EnableClientAccess()]
public class PracticeManagerDomainService : DomainService
{
    private TaskDataContext taskContext;

    public IEnumerable<Task> GetTasks()
    {
        var cnxString = ConfigurationManager.ConnectionStrings["PracticeModelContainer"].ConnectionString;
        taskContext = new TaskDataContext(cnxString);
        var tasks = taskContext.Tasks;

        return tasks;
    }
}

 

This is far from pretty, I need to move my connection string out of the method, but this will work.

On the client side

In my code behind I have two methods.

public void LoadTasks()
{
    EntityQuery<Task> taskQuery = _practiceManagerDomainContext.GetTasksQuery();
    _practiceManagerDomainContext.Load(taskQuery, this.OnTasksLoaded, null);
}

private void OnTasksLoaded(LoadOperation<Task> loadOperation)
{
    nameComboBox.ItemsSource = _practiceManagerDomainContext.Tasks;
}

This takes care of the async load and connecting to the service.

The Task object comes across because of its exposure in the domain service class.

The namespace is even the same as the server side, which indicates it is the same object. Not just a service proxy.

Once I call the LoadTasks method, I will get a dropdown populated with tasks.

That is all I need to do.

9
Dec/09
0

Using Self Tracking Entities in Entity Framework 4 to fix the error – The object could not be added or attached …

Works with Entity Framework 4 CTP 2 and Visual Studio 2010 Beta 2

{"The object could not be added or attached because its EntityReference has an EntityKey property value that does not match the EntityKey for this object."}

I am able to to insert the first record.

But subsequent records give the above error.

The structure is: Tasks have Task Items. I am trying to save task items.

 In this example my silverlight application is initiating this service call.
The task object is set by a dropdown on the client  side.

 
        public void InsertTaskItem(Task task, string value, DateTime dateTime)
        {
            TaskItem taskItem = new TaskItem();
 
            taskItem.Task = task;
            taskItem.TaskId = task.Id;
            taskItem.Value = value;
            taskItem.OccurrenceTime = dateTime;
 
            taskItem.CreatedTime = DateTime.Now;
            taskItem.ModifiedTime = DateTime.Now;
 
            this.objectContext.AddToTaskItems(taskItem);
            this.objectContext.SaveChanges();
        }

First Attempt Lets just atttach the object, it should be that easy right?

        public void InsertTaskItem(Task task, string value, DateTime dateTime)
        {
            TaskItem taskItem = new TaskItem();
 
            taskItem.Task = task;
            taskItem.TaskId = task.Id;
            taskItem.Value = value;
            taskItem.OccurrenceTime = dateTime;
 
            taskItem.CreatedTime = DateTime.Now;
            taskItem.ModifiedTime = DateTime.Now;
 
            objectContext.AttachTo(&quot;PracticeManager.Server.Business.Data.PracticeModelContainer.TaskItem&quot;, taskItem);
            this.objectContext.SaveChanges();
 
        }

I received the error.

The provided EntitySet name must be qualified by the EntityContainer name, such as 'EntityContainerName.EntitySetName', or the DefaultContainerName property must be set for the ObjectContext.
Parameter name: entitySetName

I tried both the fully qualified type name, and the entity set name.

Since I am using .Net 4.0 and the Entity Framework,  I realized I can use some of the POCO functionality they added to facilitate this specific scenario.

I can refactor and use Self Tracking Entities to accomplish my goal the right way.

The first step is download the Entity Framework 4 CTP 2  - It did not make it into VS 2010 Beta 2.

Navigate to your model, and Add New Code Generation Item.

Select ADO.NET Self Tracking Entity Generator.

        public void InsertTaskItem(Task task, string value, DateTime dateTime)
        {
            TaskItem taskItem = new TaskItem();
 
            taskItem.Task = task;
            taskItem.TaskId = task.Id;
            taskItem.Value = value;
            taskItem.OccurrenceTime = dateTime;
 
            taskItem.CreatedTime = DateTime.Now;
            taskItem.ModifiedTime = DateTime.Now;
 
 
            using (var context = new PracticeModelContainer())
            {
                context.TaskItems.ApplyChanges(taskItem);
                context.SaveChanges();
            }
        }

Once I added the context save changes, the task item now save.

One problem is when setting the task property it is triggering the creation of a new entity, and then overwriting the foreign key with the key of the newly created task.

Once the line

taskItem.Task = task;

is commented out the save works as expected.