Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json Serializing EF object without relationships

I am trying to store a Json serialized EF object in another database.

One of the items I'm strying to store is the cart, which has some relateded tables.

How can I store the cart, without dragging its relations along (preferably without resorting to .Select() to handpick the distinct columns)

[AllowAnonymous]
public ActionResult Test() {

    using (var db = new DALEntities())
    {
        var q = db.tblCarts.SingleOrDefault(x => x.CartItemID == 4275);

        q.tblContactsExtra = null;
        q.TBLINVENTORY = null;

        var settings = new JsonSerializerSettings {PreserveReferencesHandling = PreserveReferencesHandling .Objects} ;

        var str = JsonConvert.SerializeObject(q, settings);

        return Content(str);
    }
like image 816
reidLinden Avatar asked Mar 12 '26 18:03

reidLinden


1 Answers

Unfortunately, you'll have to set your foreign keys to allow nulls. Otherwise you won't be able to achieve what you're looking to achieve. To do that, just make the ID fields nullable, something like:

public int? ContactsExtraId { get; set; }
public virtual tblContactsExtra tblContactsExtra { get; set; }

public int? InventoryId { get; set; }
public virtual TblInventory TBLINVENTORY { get; set; }
like image 133
mattytommo Avatar answered Mar 15 '26 09:03

mattytommo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!