I am trying to set up a simple one-to-many relationship where a list can have zero or more tasks and a task must have a list associated. I want to assure this behavior with a unit test but I can’t figure out how the association has to be, so that the test will fail (later I will use an ExpectedExceptionAttribute, but I don’t even know which exception will be thrown yet).
The Task can be successfully submitted, but I would like to see Linq complain about a missing List reference:
[TestMethod]
public void SavingTaskWithoutListFails()
{
var task = new Task() { Title = "Test Task", Description = "This is the task description." };
Db.Tasks.InsertOnSubmit(task);
Db.SubmitChanges();
}
My classes and associations look like this:
[Table]
public class Task
{
[Column(AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsDbGenerated = true)]
public int TaskId { get; set; }
[Column(IsPrimaryKey = true)]
public string Title { get; set; }
[Column]
public string Description { get; set; }
[Column]
public int ListId { get; set; }
private EntityRef<List> _list;
[Association(Storage = "_list", ThisKey = "ListId")]
public List List
{
get { return _list.Entity; }
set { _list.Entity = value; }
}
}
and this:
[Table]
public class List
{
[Column(AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY", IsDbGenerated = true)]
public int ListId { get; set; }
[Column(IsPrimaryKey = true)]
public string Title { get; set; }
private EntitySet<Task> _tasks;
[Association(Storage = "_tasks", OtherKey = "TaskId")]
public EntitySet<Task> Tasks
{
get { return _tasks; }
set
{
if (_tasks == null)
{
_tasks = new EntitySet<Task>();
}
_tasks.Assign(value);
}
}
}
Can anyone help with the correct association or a hint how to achieve the desired behavior?
You should use
[Column(CanBeNull = false)]for association columns to achieve that.Edit:
I moved
IsPrimaryKeytoIdinstead ofTitlefor both tables, set one side of an association asIsForeignKey=trueand fill bothThisKeyandOtherKeyfor both sides of association. When I tried to add new task without ListId value SubmitChanges throwed SlqCEException with following message:A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = FK_Task_List ]