Reputation: 177
I need a help regarding Entity Framework. I have a class that has a virtual supplier
property
public class Invoices
{
public string InvoiceNumber { get; set; }
public string Department { get; set; }
public int SupplierId{ get; set; }
[ForeignKey("SupplierId")]
public virtual Supplier SupplierDetails { get; set; }
}
Here's the structure of the supplier
class
public class Supplier
{
[Key, Column("SupplierId")]
public int Id { get; set; }
public bool IsDeleted { get; set; }
public string Name { get; set; }
[Required]
public string Address { get; set; }
public string ContactNumber { get; set; }
[Required]
[EmailAddress]
public string EmailAdd { get; set; }
}
My question is: how can I add an invoice to my context without adding a supplier exists in my database?
Here's my code for the adding
public ActionResult AddInvoice(Invoices inv)
{
context.invoices.add(inv);
return View();
}
Any help will be appreciated - hoping someone can help me. Thanks
Upvotes: 0
Views: 178
Reputation: 177
by this time ive manage to add a small code to reach the specific feat.
please see below code
public ActionResult AddNewAsset(AssetHeaderDetails entity)
{
if (IsExist<Supplier>(entity.SupplierDetails))
{
entity.SupplierId = entity.SupplierDetails.Id;
entity.SupplierDetails = null;
}
AddDataToContext(entity);
AddToLookUp("AssetItemDesc", entity.Description, entity.Description);
if(entity.AssetItemDetails != null)
{
foreach (var item in entity.AssetItemDetails)
{
AddToLookUp("AssetItemDetail", item.ItemDescription, item.ItemType);
}
}
return RedirectToAction("AddNewAsset");
}
its looks like fishy but it can manage a bit..thanks to all who comment
any better code? please comment here and i will try to change the code.. BIG THANKS .. :D
Upvotes: 0
Reputation: 168
Set the SupplierId property to a nullable int type (int?). This will allow for inserting invoices without a linked supplier.
Upvotes: 1