I am trying to use Nullable
Guid
in Entity Framework but when i tried to commit the change i am getting validation message due to foreign key is null, I have below domain class, DomainType
Class has child DomainCustomField
:-
DomainType.cs
public class DomainType
{
public Guid? Id
{
get;
set;
}
private IList<DomainCustomField> _domainCustomFields;
public string Name
{
get;
set;
}
public Guid? AccountId
{
get;
set;
}
public virtual IList<DomainCustomField> DomainCustomFields
{
get
{
return this._domainCustomFields;
}
set
{
this._domainCustomFields = value;
}
}
}
DomainCustomField.cs
public class DomainCustomField
{
public Guid? Id
{
get;
set;
}
public string Name
{
get;
set;
}
public Guid? DomainTypeId
{
get;
set;
}
}
below is mapping :-
modelBuilder.Domain<DomainCustomField>().HasKey((DomainCustomField p) => new
{
p.Id,
p.DomainTypeId
});
modelBuilder.Domain<DomainCustomField>()
.Property(p => p.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Domain<DomainType>()
.HasMany(p => p.DomainCustomFields)
.WithRequired()
.HasForeignKey<Guid?>(x => x.DomainTypeId);
below is sample code which i tried to insert.
DomainType domainType = new DomainType()
{
AccountId = customer.Id
};
domainType.DomainCustomFields.Add(new DomainCustomField()
{
Name = "Test"
});
Workspace.Add<DomainType>(domainType);
Workspace.CommitChanges();
Error :- validation error for DomainTypeId is required
in the same code if i change Guid?
to Guid
in ID variable then its work correctly. I don't know how to handle nullable
Guid
. do i need to manually set parent key in child reference? then how it works fine in case of Guid
?
Note :- I am using using Guid
because i am working with distributed database, where id can generate from multiple source system.
I am using Guid?
because by default Guid
generate 00000000-0000-0000-0000-000000000000
for empty Guid
which can grow database size.
DomainType
in the model).HasOptional
->modelBuilder.Domain<DomainCustomField>() .Property(p => p.Id)..HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).HasOptional(p=>p.DomainType)..HasForeignKey(x => x.DomainTypeId)
Id
properties need to be non-nullable.DomainTypeId
should remain as nullable.WithRequired
needs to change toHasOptional
.